123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150 |
- "use strict";
- const allLoopTypes = ["WhileStatement", "DoWhileStatement", "ForStatement", "ForInStatement", "ForOfStatement"];
- function isLoopingTarget(node) {
- const parent = node.parent;
- if (parent) {
- switch (parent.type) {
- case "WhileStatement":
- return node === parent.test;
- case "DoWhileStatement":
- return node === parent.body;
- case "ForStatement":
- return node === (parent.update || parent.test || parent.body);
- case "ForInStatement":
- case "ForOfStatement":
- return node === parent.left;
-
- }
- }
- return false;
- }
- function getDifference(arrA, arrB) {
- return arrA.filter(a => !arrB.includes(a));
- }
- module.exports = {
- meta: {
- type: "problem",
- docs: {
- description: "disallow loops with a body that allows only one iteration",
- category: "Possible Errors",
- recommended: false,
- url: "https://eslint.org/docs/rules/no-unreachable-loop"
- },
- schema: [{
- type: "object",
- properties: {
- ignore: {
- type: "array",
- items: {
- enum: allLoopTypes
- },
- uniqueItems: true
- }
- },
- additionalProperties: false
- }],
- messages: {
- invalid: "Invalid loop. Its body allows only one iteration."
- }
- },
- create(context) {
- const ignoredLoopTypes = context.options[0] && context.options[0].ignore || [],
- loopTypesToCheck = getDifference(allLoopTypes, ignoredLoopTypes),
- loopSelector = loopTypesToCheck.join(","),
- loopsByTargetSegments = new Map(),
- loopsToReport = new Set();
- let currentCodePath = null;
- return {
- onCodePathStart(codePath) {
- currentCodePath = codePath;
- },
- onCodePathEnd() {
- currentCodePath = currentCodePath.upper;
- },
- [loopSelector](node) {
-
- if (currentCodePath.currentSegments.some(segment => segment.reachable)) {
- loopsToReport.add(node);
- }
- },
- onCodePathSegmentStart(segment, node) {
- if (isLoopingTarget(node)) {
- const loop = node.parent;
- loopsByTargetSegments.set(segment, loop);
- }
- },
- onCodePathSegmentLoop(_, toSegment, node) {
- const loop = loopsByTargetSegments.get(toSegment);
-
- if (node === loop || node.type === "ContinueStatement") {
-
- loopsToReport.delete(loop);
- }
- },
- "Program:exit"() {
- loopsToReport.forEach(
- node => context.report({ node, messageId: "invalid" })
- );
- }
- };
- }
- };
|