Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
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 9.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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 astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Helpers
  12. //------------------------------------------------------------------------------
  13. const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u;
  14. const TARGET_METHODS = /^(?:every|filter|find(?:Index)?|flatMap|forEach|map|reduce(?:Right)?|some|sort)$/u;
  15. /**
  16. * Checks a given code path segment is reachable.
  17. * @param {CodePathSegment} segment A segment to check.
  18. * @returns {boolean} `true` if the segment is reachable.
  19. */
  20. function isReachable(segment) {
  21. return segment.reachable;
  22. }
  23. /**
  24. * Checks a given node is a member access which has the specified name's
  25. * property.
  26. * @param {ASTNode} node A node to check.
  27. * @returns {boolean} `true` if the node is a member access which has
  28. * the specified name's property. The node may be a `(Chain|Member)Expression` node.
  29. */
  30. function isTargetMethod(node) {
  31. return astUtils.isSpecificMemberAccess(node, null, TARGET_METHODS);
  32. }
  33. /**
  34. * Returns a human-legible description of an array method
  35. * @param {string} arrayMethodName A method name to fully qualify
  36. * @returns {string} the method name prefixed with `Array.` if it is a class method,
  37. * or else `Array.prototype.` if it is an instance method.
  38. */
  39. function fullMethodName(arrayMethodName) {
  40. if (["from", "of", "isArray"].includes(arrayMethodName)) {
  41. return "Array.".concat(arrayMethodName);
  42. }
  43. return "Array.prototype.".concat(arrayMethodName);
  44. }
  45. /**
  46. * Checks whether or not a given node is a function expression which is the
  47. * callback of an array method, returning the method name.
  48. * @param {ASTNode} node A node to check. This is one of
  49. * FunctionExpression or ArrowFunctionExpression.
  50. * @returns {string} The method name if the node is a callback method,
  51. * null otherwise.
  52. */
  53. function getArrayMethodName(node) {
  54. let currentNode = node;
  55. while (currentNode) {
  56. const parent = currentNode.parent;
  57. switch (parent.type) {
  58. /*
  59. * Looks up the destination. e.g.,
  60. * foo.every(nativeFoo || function foo() { ... });
  61. */
  62. case "LogicalExpression":
  63. case "ConditionalExpression":
  64. case "ChainExpression":
  65. currentNode = parent;
  66. break;
  67. /*
  68. * If the upper function is IIFE, checks the destination of the return value.
  69. * e.g.
  70. * foo.every((function() {
  71. * // setup...
  72. * return function callback() { ... };
  73. * })());
  74. */
  75. case "ReturnStatement": {
  76. const func = astUtils.getUpperFunction(parent);
  77. if (func === null || !astUtils.isCallee(func)) {
  78. return null;
  79. }
  80. currentNode = func.parent;
  81. break;
  82. }
  83. /*
  84. * e.g.
  85. * Array.from([], function() {});
  86. * list.every(function() {});
  87. */
  88. case "CallExpression":
  89. if (astUtils.isArrayFromMethod(parent.callee)) {
  90. if (
  91. parent.arguments.length >= 2 &&
  92. parent.arguments[1] === currentNode
  93. ) {
  94. return "from";
  95. }
  96. }
  97. if (isTargetMethod(parent.callee)) {
  98. if (
  99. parent.arguments.length >= 1 &&
  100. parent.arguments[0] === currentNode
  101. ) {
  102. return astUtils.getStaticPropertyName(parent.callee);
  103. }
  104. }
  105. return null;
  106. // Otherwise this node is not target.
  107. default:
  108. return null;
  109. }
  110. }
  111. /* istanbul ignore next: unreachable */
  112. return null;
  113. }
  114. //------------------------------------------------------------------------------
  115. // Rule Definition
  116. //------------------------------------------------------------------------------
  117. module.exports = {
  118. meta: {
  119. type: "problem",
  120. docs: {
  121. description: "enforce `return` statements in callbacks of array methods",
  122. category: "Best Practices",
  123. recommended: false,
  124. url: "https://eslint.org/docs/rules/array-callback-return"
  125. },
  126. schema: [
  127. {
  128. type: "object",
  129. properties: {
  130. allowImplicit: {
  131. type: "boolean",
  132. default: false
  133. },
  134. checkForEach: {
  135. type: "boolean",
  136. default: false
  137. }
  138. },
  139. additionalProperties: false
  140. }
  141. ],
  142. messages: {
  143. expectedAtEnd: "{{arrayMethodName}}() expects a value to be returned at the end of {{name}}.",
  144. expectedInside: "{{arrayMethodName}}() expects a return value from {{name}}.",
  145. expectedReturnValue: "{{arrayMethodName}}() expects a return value from {{name}}.",
  146. expectedNoReturnValue: "{{arrayMethodName}}() expects no useless return value from {{name}}."
  147. }
  148. },
  149. create(context) {
  150. const options = context.options[0] || { allowImplicit: false, checkForEach: false };
  151. const sourceCode = context.getSourceCode();
  152. let funcInfo = {
  153. arrayMethodName: null,
  154. upper: null,
  155. codePath: null,
  156. hasReturn: false,
  157. shouldCheck: false,
  158. node: null
  159. };
  160. /**
  161. * Checks whether or not the last code path segment is reachable.
  162. * Then reports this function if the segment is reachable.
  163. *
  164. * If the last code path segment is reachable, there are paths which are not
  165. * returned or thrown.
  166. * @param {ASTNode} node A node to check.
  167. * @returns {void}
  168. */
  169. function checkLastSegment(node) {
  170. if (!funcInfo.shouldCheck) {
  171. return;
  172. }
  173. let messageId = null;
  174. if (funcInfo.arrayMethodName === "forEach") {
  175. if (options.checkForEach && node.type === "ArrowFunctionExpression" && node.expression) {
  176. messageId = "expectedNoReturnValue";
  177. }
  178. } else {
  179. if (node.body.type === "BlockStatement" && funcInfo.codePath.currentSegments.some(isReachable)) {
  180. messageId = funcInfo.hasReturn ? "expectedAtEnd" : "expectedInside";
  181. }
  182. }
  183. if (messageId) {
  184. const name = astUtils.getFunctionNameWithKind(node);
  185. context.report({
  186. node,
  187. loc: astUtils.getFunctionHeadLoc(node, sourceCode),
  188. messageId,
  189. data: { name, arrayMethodName: fullMethodName(funcInfo.arrayMethodName) }
  190. });
  191. }
  192. }
  193. return {
  194. // Stacks this function's information.
  195. onCodePathStart(codePath, node) {
  196. let methodName = null;
  197. if (TARGET_NODE_TYPE.test(node.type)) {
  198. methodName = getArrayMethodName(node);
  199. }
  200. funcInfo = {
  201. arrayMethodName: methodName,
  202. upper: funcInfo,
  203. codePath,
  204. hasReturn: false,
  205. shouldCheck:
  206. methodName &&
  207. !node.async &&
  208. !node.generator,
  209. node
  210. };
  211. },
  212. // Pops this function's information.
  213. onCodePathEnd() {
  214. funcInfo = funcInfo.upper;
  215. },
  216. // Checks the return statement is valid.
  217. ReturnStatement(node) {
  218. if (!funcInfo.shouldCheck) {
  219. return;
  220. }
  221. funcInfo.hasReturn = true;
  222. let messageId = null;
  223. if (funcInfo.arrayMethodName === "forEach") {
  224. // if checkForEach: true, returning a value at any path inside a forEach is not allowed
  225. if (options.checkForEach && node.argument) {
  226. messageId = "expectedNoReturnValue";
  227. }
  228. } else {
  229. // if allowImplicit: false, should also check node.argument
  230. if (!options.allowImplicit && !node.argument) {
  231. messageId = "expectedReturnValue";
  232. }
  233. }
  234. if (messageId) {
  235. context.report({
  236. node,
  237. messageId,
  238. data: {
  239. name: astUtils.getFunctionNameWithKind(funcInfo.node),
  240. arrayMethodName: fullMethodName(funcInfo.arrayMethodName)
  241. }
  242. });
  243. }
  244. },
  245. // Reports a given function if the last path is reachable.
  246. "FunctionExpression:exit": checkLastSegment,
  247. "ArrowFunctionExpression:exit": checkLastSegment
  248. };
  249. }
  250. };