no-unreachable-loop.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. /**
  2. * @fileoverview Rule to disallow loops with a body that allows only one iteration
  3. * @author Milos Djermanovic
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Helpers
  8. //------------------------------------------------------------------------------
  9. const allLoopTypes = [
  10. "WhileStatement",
  11. "DoWhileStatement",
  12. "ForStatement",
  13. "ForInStatement",
  14. "ForOfStatement",
  15. ];
  16. /**
  17. * Checks all segments in a set and returns true if any are reachable.
  18. * @param {Set<CodePathSegment>} segments The segments to check.
  19. * @returns {boolean} True if any segment is reachable; false otherwise.
  20. */
  21. function isAnySegmentReachable(segments) {
  22. for (const segment of segments) {
  23. if (segment.reachable) {
  24. return true;
  25. }
  26. }
  27. return false;
  28. }
  29. /**
  30. * Determines whether the given node is the first node in the code path to which a loop statement
  31. * 'loops' for the next iteration.
  32. * @param {ASTNode} node The node to check.
  33. * @returns {boolean} `true` if the node is a looping target.
  34. */
  35. function isLoopingTarget(node) {
  36. const parent = node.parent;
  37. if (parent) {
  38. switch (parent.type) {
  39. case "WhileStatement":
  40. return node === parent.test;
  41. case "DoWhileStatement":
  42. return node === parent.body;
  43. case "ForStatement":
  44. return node === (parent.update || parent.test || parent.body);
  45. case "ForInStatement":
  46. case "ForOfStatement":
  47. return node === parent.left;
  48. // no default
  49. }
  50. }
  51. return false;
  52. }
  53. /**
  54. * Creates an array with elements from the first given array that are not included in the second given array.
  55. * @param {Array} arrA The array to compare from.
  56. * @param {Array} arrB The array to compare against.
  57. * @returns {Array} a new array that represents `arrA \ arrB`.
  58. */
  59. function getDifference(arrA, arrB) {
  60. return arrA.filter(a => !arrB.includes(a));
  61. }
  62. //------------------------------------------------------------------------------
  63. // Rule Definition
  64. //------------------------------------------------------------------------------
  65. /** @type {import('../types').Rule.RuleModule} */
  66. module.exports = {
  67. meta: {
  68. type: "problem",
  69. defaultOptions: [{ ignore: [] }],
  70. docs: {
  71. description:
  72. "Disallow loops with a body that allows only one iteration",
  73. recommended: false,
  74. url: "https://eslint.org/docs/latest/rules/no-unreachable-loop",
  75. },
  76. schema: [
  77. {
  78. type: "object",
  79. properties: {
  80. ignore: {
  81. type: "array",
  82. items: {
  83. enum: allLoopTypes,
  84. },
  85. uniqueItems: true,
  86. },
  87. },
  88. additionalProperties: false,
  89. },
  90. ],
  91. messages: {
  92. invalid: "Invalid loop. Its body allows only one iteration.",
  93. },
  94. },
  95. create(context) {
  96. const [{ ignore: ignoredLoopTypes }] = context.options;
  97. const loopTypesToCheck = getDifference(allLoopTypes, ignoredLoopTypes),
  98. loopSelector = loopTypesToCheck.join(","),
  99. loopsByTargetSegments = new Map(),
  100. loopsToReport = new Set();
  101. const codePathSegments = [];
  102. let currentCodePathSegments = new Set();
  103. return {
  104. onCodePathStart() {
  105. codePathSegments.push(currentCodePathSegments);
  106. currentCodePathSegments = new Set();
  107. },
  108. onCodePathEnd() {
  109. currentCodePathSegments = codePathSegments.pop();
  110. },
  111. onUnreachableCodePathSegmentStart(segment) {
  112. currentCodePathSegments.add(segment);
  113. },
  114. onUnreachableCodePathSegmentEnd(segment) {
  115. currentCodePathSegments.delete(segment);
  116. },
  117. onCodePathSegmentEnd(segment) {
  118. currentCodePathSegments.delete(segment);
  119. },
  120. onCodePathSegmentStart(segment, node) {
  121. currentCodePathSegments.add(segment);
  122. if (isLoopingTarget(node)) {
  123. const loop = node.parent;
  124. loopsByTargetSegments.set(segment, loop);
  125. }
  126. },
  127. onCodePathSegmentLoop(_, toSegment, node) {
  128. const loop = loopsByTargetSegments.get(toSegment);
  129. /**
  130. * The second iteration is reachable, meaning that the loop is valid by the logic of this rule,
  131. * only if there is at least one loop event with the appropriate target (which has been already
  132. * determined in the `loopsByTargetSegments` map), raised from either:
  133. *
  134. * - the end of the loop's body (in which case `node === loop`)
  135. * - a `continue` statement
  136. *
  137. * This condition skips loop events raised from `ForInStatement > .right` and `ForOfStatement > .right` nodes.
  138. */
  139. if (node === loop || node.type === "ContinueStatement") {
  140. // Removes loop if it exists in the set. Otherwise, `Set#delete` has no effect and doesn't throw.
  141. loopsToReport.delete(loop);
  142. }
  143. },
  144. [loopSelector](node) {
  145. /**
  146. * Ignore unreachable loop statements to avoid unnecessary complexity in the implementation, or false positives otherwise.
  147. * For unreachable segments, the code path analysis does not raise events required for this implementation.
  148. */
  149. if (isAnySegmentReachable(currentCodePathSegments)) {
  150. loopsToReport.add(node);
  151. }
  152. },
  153. "Program:exit"() {
  154. loopsToReport.forEach(node =>
  155. context.report({ node, messageId: "invalid" }),
  156. );
  157. },
  158. };
  159. },
  160. };