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.

array-callback-return.js 7.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. /**
  2. * @fileoverview Rule to enforce return statements in callbacks of array's methods
  3. * @author Toru Nagashima
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const lodash = require("lodash");
  10. const astUtils = require("../util/ast-utils");
  11. //------------------------------------------------------------------------------
  12. // Helpers
  13. //------------------------------------------------------------------------------
  14. const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/;
  15. const TARGET_METHODS = /^(?:every|filter|find(?:Index)?|map|reduce(?:Right)?|some|sort)$/;
  16. /**
  17. * Checks a given code path segment is reachable.
  18. *
  19. * @param {CodePathSegment} segment - A segment to check.
  20. * @returns {boolean} `true` if the segment is reachable.
  21. */
  22. function isReachable(segment) {
  23. return segment.reachable;
  24. }
  25. /**
  26. * Gets a readable location.
  27. *
  28. * - FunctionExpression -> the function name or `function` keyword.
  29. * - ArrowFunctionExpression -> `=>` token.
  30. *
  31. * @param {ASTNode} node - A function node to get.
  32. * @param {SourceCode} sourceCode - A source code to get tokens.
  33. * @returns {ASTNode|Token} The node or the token of a location.
  34. */
  35. function getLocation(node, sourceCode) {
  36. if (node.type === "ArrowFunctionExpression") {
  37. return sourceCode.getTokenBefore(node.body);
  38. }
  39. return node.id || node;
  40. }
  41. /**
  42. * Checks a given node is a MemberExpression node which has the specified name's
  43. * property.
  44. *
  45. * @param {ASTNode} node - A node to check.
  46. * @returns {boolean} `true` if the node is a MemberExpression node which has
  47. * the specified name's property
  48. */
  49. function isTargetMethod(node) {
  50. return (
  51. node.type === "MemberExpression" &&
  52. TARGET_METHODS.test(astUtils.getStaticPropertyName(node) || "")
  53. );
  54. }
  55. /**
  56. * Checks whether or not a given node is a function expression which is the
  57. * callback of an array method.
  58. *
  59. * @param {ASTNode} node - A node to check. This is one of
  60. * FunctionExpression or ArrowFunctionExpression.
  61. * @returns {boolean} `true` if the node is the callback of an array method.
  62. */
  63. function isCallbackOfArrayMethod(node) {
  64. let currentNode = node;
  65. while (currentNode) {
  66. const parent = currentNode.parent;
  67. switch (parent.type) {
  68. /*
  69. * Looks up the destination. e.g.,
  70. * foo.every(nativeFoo || function foo() { ... });
  71. */
  72. case "LogicalExpression":
  73. case "ConditionalExpression":
  74. currentNode = parent;
  75. break;
  76. /*
  77. * If the upper function is IIFE, checks the destination of the return value.
  78. * e.g.
  79. * foo.every((function() {
  80. * // setup...
  81. * return function callback() { ... };
  82. * })());
  83. */
  84. case "ReturnStatement": {
  85. const func = astUtils.getUpperFunction(parent);
  86. if (func === null || !astUtils.isCallee(func)) {
  87. return false;
  88. }
  89. currentNode = func.parent;
  90. break;
  91. }
  92. /*
  93. * e.g.
  94. * Array.from([], function() {});
  95. * list.every(function() {});
  96. */
  97. case "CallExpression":
  98. if (astUtils.isArrayFromMethod(parent.callee)) {
  99. return (
  100. parent.arguments.length >= 2 &&
  101. parent.arguments[1] === currentNode
  102. );
  103. }
  104. if (isTargetMethod(parent.callee)) {
  105. return (
  106. parent.arguments.length >= 1 &&
  107. parent.arguments[0] === currentNode
  108. );
  109. }
  110. return false;
  111. // Otherwise this node is not target.
  112. default:
  113. return false;
  114. }
  115. }
  116. /* istanbul ignore next: unreachable */
  117. return false;
  118. }
  119. //------------------------------------------------------------------------------
  120. // Rule Definition
  121. //------------------------------------------------------------------------------
  122. module.exports = {
  123. meta: {
  124. type: "problem",
  125. docs: {
  126. description: "enforce `return` statements in callbacks of array methods",
  127. category: "Best Practices",
  128. recommended: false,
  129. url: "https://eslint.org/docs/rules/array-callback-return"
  130. },
  131. schema: [
  132. {
  133. type: "object",
  134. properties: {
  135. allowImplicit: {
  136. type: "boolean"
  137. }
  138. },
  139. additionalProperties: false
  140. }
  141. ],
  142. messages: {
  143. expectedAtEnd: "Expected to return a value at the end of {{name}}.",
  144. expectedInside: "Expected to return a value in {{name}}.",
  145. expectedReturnValue: "{{name}} expected a return value."
  146. }
  147. },
  148. create(context) {
  149. const options = context.options[0] || { allowImplicit: false };
  150. let funcInfo = {
  151. upper: null,
  152. codePath: null,
  153. hasReturn: false,
  154. shouldCheck: false,
  155. node: null
  156. };
  157. /**
  158. * Checks whether or not the last code path segment is reachable.
  159. * Then reports this function if the segment is reachable.
  160. *
  161. * If the last code path segment is reachable, there are paths which are not
  162. * returned or thrown.
  163. *
  164. * @param {ASTNode} node - A node to check.
  165. * @returns {void}
  166. */
  167. function checkLastSegment(node) {
  168. if (funcInfo.shouldCheck &&
  169. funcInfo.codePath.currentSegments.some(isReachable)
  170. ) {
  171. context.report({
  172. node,
  173. loc: getLocation(node, context.getSourceCode()).loc.start,
  174. messageId: funcInfo.hasReturn
  175. ? "expectedAtEnd"
  176. : "expectedInside",
  177. data: {
  178. name: astUtils.getFunctionNameWithKind(funcInfo.node)
  179. }
  180. });
  181. }
  182. }
  183. return {
  184. // Stacks this function's information.
  185. onCodePathStart(codePath, node) {
  186. funcInfo = {
  187. upper: funcInfo,
  188. codePath,
  189. hasReturn: false,
  190. shouldCheck:
  191. TARGET_NODE_TYPE.test(node.type) &&
  192. node.body.type === "BlockStatement" &&
  193. isCallbackOfArrayMethod(node) &&
  194. !node.async &&
  195. !node.generator,
  196. node
  197. };
  198. },
  199. // Pops this function's information.
  200. onCodePathEnd() {
  201. funcInfo = funcInfo.upper;
  202. },
  203. // Checks the return statement is valid.
  204. ReturnStatement(node) {
  205. if (funcInfo.shouldCheck) {
  206. funcInfo.hasReturn = true;
  207. // if allowImplicit: false, should also check node.argument
  208. if (!options.allowImplicit && !node.argument) {
  209. context.report({
  210. node,
  211. messageId: "expectedReturnValue",
  212. data: {
  213. name: lodash.upperFirst(astUtils.getFunctionNameWithKind(funcInfo.node))
  214. }
  215. });
  216. }
  217. }
  218. },
  219. // Reports a given function if the last path is reachable.
  220. "FunctionExpression:exit": checkLastSegment,
  221. "ArrowFunctionExpression:exit": checkLastSegment
  222. };
  223. }
  224. };