no-array-callback-reference.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. 'use strict';
  2. const {isParenthesized} = require('@eslint-community/eslint-utils');
  3. const {methodCallSelector, notFunctionSelector} = require('./selectors/index.js');
  4. const {isNodeMatches} = require('./utils/is-node-matches.js');
  5. const ERROR_WITH_NAME_MESSAGE_ID = 'error-with-name';
  6. const ERROR_WITHOUT_NAME_MESSAGE_ID = 'error-without-name';
  7. const REPLACE_WITH_NAME_MESSAGE_ID = 'replace-with-name';
  8. const REPLACE_WITHOUT_NAME_MESSAGE_ID = 'replace-without-name';
  9. const messages = {
  10. [ERROR_WITH_NAME_MESSAGE_ID]: 'Do not pass function `{{name}}` directly to `.{{method}}(…)`.',
  11. [ERROR_WITHOUT_NAME_MESSAGE_ID]: 'Do not pass function directly to `.{{method}}(…)`.',
  12. [REPLACE_WITH_NAME_MESSAGE_ID]: 'Replace function `{{name}}` with `… => {{name}}({{parameters}})`.',
  13. [REPLACE_WITHOUT_NAME_MESSAGE_ID]: 'Replace function with `… => …({{parameters}})`.',
  14. };
  15. const iteratorMethods = [
  16. [
  17. 'every',
  18. {
  19. ignore: [
  20. 'Boolean',
  21. ],
  22. },
  23. ],
  24. [
  25. 'filter', {
  26. extraSelector: '[callee.object.name!="Vue"]',
  27. ignore: [
  28. 'Boolean',
  29. ],
  30. },
  31. ],
  32. [
  33. 'find',
  34. {
  35. ignore: [
  36. 'Boolean',
  37. ],
  38. },
  39. ],
  40. [
  41. 'findLast',
  42. {
  43. ignore: [
  44. 'Boolean',
  45. ],
  46. },
  47. ],
  48. [
  49. 'findIndex',
  50. {
  51. ignore: [
  52. 'Boolean',
  53. ],
  54. },
  55. ],
  56. [
  57. 'findLastIndex',
  58. {
  59. ignore: [
  60. 'Boolean',
  61. ],
  62. },
  63. ],
  64. [
  65. 'flatMap',
  66. ],
  67. [
  68. 'forEach',
  69. {
  70. returnsUndefined: true,
  71. },
  72. ],
  73. [
  74. 'map',
  75. {
  76. extraSelector: '[callee.object.name!="types"]',
  77. ignore: [
  78. 'String',
  79. 'Number',
  80. 'BigInt',
  81. 'Boolean',
  82. 'Symbol',
  83. ],
  84. },
  85. ],
  86. [
  87. 'reduce',
  88. {
  89. parameters: [
  90. 'accumulator',
  91. 'element',
  92. 'index',
  93. 'array',
  94. ],
  95. minParameters: 2,
  96. },
  97. ],
  98. [
  99. 'reduceRight',
  100. {
  101. parameters: [
  102. 'accumulator',
  103. 'element',
  104. 'index',
  105. 'array',
  106. ],
  107. minParameters: 2,
  108. },
  109. ],
  110. [
  111. 'some',
  112. {
  113. ignore: [
  114. 'Boolean',
  115. ],
  116. },
  117. ],
  118. ].map(([method, options]) => {
  119. options = {
  120. parameters: ['element', 'index', 'array'],
  121. ignore: [],
  122. minParameters: 1,
  123. extraSelector: '',
  124. returnsUndefined: false,
  125. ...options,
  126. };
  127. return [method, options];
  128. });
  129. const ignoredCallee = [
  130. // http://bluebirdjs.com/docs/api/promise.map.html
  131. 'Promise',
  132. 'React.Children',
  133. 'Children',
  134. 'lodash',
  135. 'underscore',
  136. '_',
  137. 'Async',
  138. 'async',
  139. 'this',
  140. '$',
  141. 'jQuery',
  142. ];
  143. function getProblem(context, node, method, options) {
  144. const {type} = node;
  145. const name = type === 'Identifier' ? node.name : '';
  146. if (type === 'Identifier' && options.ignore.includes(name)) {
  147. return;
  148. }
  149. const problem = {
  150. node,
  151. messageId: name ? ERROR_WITH_NAME_MESSAGE_ID : ERROR_WITHOUT_NAME_MESSAGE_ID,
  152. data: {
  153. name,
  154. method,
  155. },
  156. suggest: [],
  157. };
  158. const {parameters, minParameters, returnsUndefined} = options;
  159. for (let parameterLength = minParameters; parameterLength <= parameters.length; parameterLength++) {
  160. const suggestionParameters = parameters.slice(0, parameterLength).join(', ');
  161. const suggest = {
  162. messageId: name ? REPLACE_WITH_NAME_MESSAGE_ID : REPLACE_WITHOUT_NAME_MESSAGE_ID,
  163. data: {
  164. name,
  165. parameters: suggestionParameters,
  166. },
  167. fix(fixer) {
  168. const sourceCode = context.getSourceCode();
  169. let nodeText = sourceCode.getText(node);
  170. if (isParenthesized(node, sourceCode) || type === 'ConditionalExpression') {
  171. nodeText = `(${nodeText})`;
  172. }
  173. return fixer.replaceText(
  174. node,
  175. returnsUndefined
  176. ? `(${suggestionParameters}) => { ${nodeText}(${suggestionParameters}); }`
  177. : `(${suggestionParameters}) => ${nodeText}(${suggestionParameters})`,
  178. );
  179. },
  180. };
  181. problem.suggest.push(suggest);
  182. }
  183. return problem;
  184. }
  185. const ignoredFirstArgumentSelector = [
  186. notFunctionSelector('arguments.0'),
  187. // Ignore all `CallExpression`s include `function.bind()`
  188. '[arguments.0.type!="CallExpression"]',
  189. '[arguments.0.type!="FunctionExpression"]',
  190. '[arguments.0.type!="ArrowFunctionExpression"]',
  191. ].join('');
  192. /** @param {import('eslint').Rule.RuleContext} context */
  193. const create = context => {
  194. const rules = {};
  195. for (const [method, options] of iteratorMethods) {
  196. const selector = [
  197. method === 'reduce' || method === 'reduceRight' ? '' : ':not(AwaitExpression) > ',
  198. methodCallSelector({
  199. method,
  200. minimumArguments: 1,
  201. maximumArguments: 2,
  202. }),
  203. options.extraSelector,
  204. ignoredFirstArgumentSelector,
  205. ].join('');
  206. rules[selector] = node => {
  207. if (isNodeMatches(node.callee.object, ignoredCallee)) {
  208. return;
  209. }
  210. if (node.callee.object.type === 'CallExpression' && isNodeMatches(node.callee.object.callee, ignoredCallee)) {
  211. return;
  212. }
  213. const [iterator] = node.arguments;
  214. return getProblem(context, iterator, method, options);
  215. };
  216. }
  217. return rules;
  218. };
  219. /** @type {import('eslint').Rule.RuleModule} */
  220. module.exports = {
  221. create,
  222. meta: {
  223. type: 'problem',
  224. docs: {
  225. description: 'Prevent passing a function reference directly to iterator methods.',
  226. },
  227. hasSuggestions: true,
  228. messages,
  229. },
  230. };