no-loop-func.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. /**
  2. * @fileoverview Rule to flag creation of function inside a loop
  3. * @author Ilya Volodin
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Helpers
  8. //------------------------------------------------------------------------------
  9. /**
  10. * Gets the containing loop node of a specified node.
  11. *
  12. * We don't need to check nested functions, so this ignores those.
  13. * `Scope.through` contains references of nested functions.
  14. * @param {ASTNode} node An AST node to get.
  15. * @returns {ASTNode|null} The containing loop node of the specified node, or
  16. * `null`.
  17. */
  18. function getContainingLoopNode(node) {
  19. for (let currentNode = node; currentNode.parent; currentNode = currentNode.parent) {
  20. const parent = currentNode.parent;
  21. switch (parent.type) {
  22. case "WhileStatement":
  23. case "DoWhileStatement":
  24. return parent;
  25. case "ForStatement":
  26. // `init` is outside of the loop.
  27. if (parent.init !== currentNode) {
  28. return parent;
  29. }
  30. break;
  31. case "ForInStatement":
  32. case "ForOfStatement":
  33. // `right` is outside of the loop.
  34. if (parent.right !== currentNode) {
  35. return parent;
  36. }
  37. break;
  38. case "ArrowFunctionExpression":
  39. case "FunctionExpression":
  40. case "FunctionDeclaration":
  41. // We don't need to check nested functions.
  42. return null;
  43. default:
  44. break;
  45. }
  46. }
  47. return null;
  48. }
  49. /**
  50. * Gets the containing loop node of a given node.
  51. * If the loop was nested, this returns the most outer loop.
  52. * @param {ASTNode} node A node to get. This is a loop node.
  53. * @param {ASTNode|null} excludedNode A node that the result node should not
  54. * include.
  55. * @returns {ASTNode} The most outer loop node.
  56. */
  57. function getTopLoopNode(node, excludedNode) {
  58. const border = excludedNode ? excludedNode.range[1] : 0;
  59. let retv = node;
  60. let containingLoopNode = node;
  61. while (containingLoopNode && containingLoopNode.range[0] >= border) {
  62. retv = containingLoopNode;
  63. containingLoopNode = getContainingLoopNode(containingLoopNode);
  64. }
  65. return retv;
  66. }
  67. /**
  68. * Checks whether a given reference which refers to an upper scope's variable is
  69. * safe or not.
  70. * @param {ASTNode} loopNode A containing loop node.
  71. * @param {eslint-scope.Reference} reference A reference to check.
  72. * @returns {boolean} `true` if the reference is safe or not.
  73. */
  74. function isSafe(loopNode, reference) {
  75. const variable = reference.resolved;
  76. const definition = variable && variable.defs[0];
  77. const declaration = definition && definition.parent;
  78. const kind = (declaration && declaration.type === "VariableDeclaration")
  79. ? declaration.kind
  80. : "";
  81. // Variables which are declared by `const` is safe.
  82. if (kind === "const") {
  83. return true;
  84. }
  85. /*
  86. * Variables which are declared by `let` in the loop is safe.
  87. * It's a different instance from the next loop step's.
  88. */
  89. if (kind === "let" &&
  90. declaration.range[0] > loopNode.range[0] &&
  91. declaration.range[1] < loopNode.range[1]
  92. ) {
  93. return true;
  94. }
  95. /*
  96. * WriteReferences which exist after this border are unsafe because those
  97. * can modify the variable.
  98. */
  99. const border = getTopLoopNode(
  100. loopNode,
  101. (kind === "let") ? declaration : null
  102. ).range[0];
  103. /**
  104. * Checks whether a given reference is safe or not.
  105. * The reference is every reference of the upper scope's variable we are
  106. * looking now.
  107. *
  108. * It's safeafe if the reference matches one of the following condition.
  109. * - is readonly.
  110. * - doesn't exist inside a local function and after the border.
  111. * @param {eslint-scope.Reference} upperRef A reference to check.
  112. * @returns {boolean} `true` if the reference is safe.
  113. */
  114. function isSafeReference(upperRef) {
  115. const id = upperRef.identifier;
  116. return (
  117. !upperRef.isWrite() ||
  118. variable.scope.variableScope === upperRef.from.variableScope &&
  119. id.range[0] < border
  120. );
  121. }
  122. return Boolean(variable) && variable.references.every(isSafeReference);
  123. }
  124. //------------------------------------------------------------------------------
  125. // Rule Definition
  126. //------------------------------------------------------------------------------
  127. module.exports = {
  128. meta: {
  129. type: "suggestion",
  130. docs: {
  131. description: "disallow function declarations that contain unsafe references inside loop statements",
  132. category: "Best Practices",
  133. recommended: false,
  134. url: "https://eslint.org/docs/rules/no-loop-func"
  135. },
  136. schema: [],
  137. messages: {
  138. unsafeRefs: "Function declared in a loop contains unsafe references to variable(s) {{ varNames }}."
  139. }
  140. },
  141. create(context) {
  142. /**
  143. * Reports functions which match the following condition:
  144. *
  145. * - has a loop node in ancestors.
  146. * - has any references which refers to an unsafe variable.
  147. * @param {ASTNode} node The AST node to check.
  148. * @returns {boolean} Whether or not the node is within a loop.
  149. */
  150. function checkForLoops(node) {
  151. const loopNode = getContainingLoopNode(node);
  152. if (!loopNode) {
  153. return;
  154. }
  155. const references = context.getScope().through;
  156. const unsafeRefs = references.filter(r => !isSafe(loopNode, r)).map(r => r.identifier.name);
  157. if (unsafeRefs.length > 0) {
  158. context.report({
  159. node,
  160. messageId: "unsafeRefs",
  161. data: { varNames: `'${unsafeRefs.join("', '")}'` }
  162. });
  163. }
  164. }
  165. return {
  166. ArrowFunctionExpression: checkForLoops,
  167. FunctionExpression: checkForLoops,
  168. FunctionDeclaration: checkForLoops
  169. };
  170. }
  171. };