Skip to content

Commit

Permalink
Merge pull request #13 from node-red/fix-loops
Browse files Browse the repository at this point in the history
Improve no-loop detection
  • Loading branch information
knolleary authored Jul 26, 2021
2 parents 8794722 + e7274f2 commit f71dc9c
Showing 1 changed file with 34 additions and 23 deletions.
57 changes: 34 additions & 23 deletions lib/rules/no-loops.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,38 @@ module.exports = {
create: function(context, ruleConfig) {

let checked = {};
let stack = {};

let followLinkNodes = false;
if (ruleConfig.hasOwnProperty('followLinkNodes')) {
followLinkNodes = ruleConfig.followLinkNodes;
}

function checkNode(node) {
function checkNodeGraph(node) {
let result = new Set();
if (stack[node.id]) {
result.add(node.id);
return result;
}
if (checked[node.id]) {
return result;
}

checked[node.id] = true;
stack[node.id] = true;
let next = node.getNextNodes(followLinkNodes);
for (let i=0; i<next.length; i++) {
let nextResult = checkNodeGraph(next[i]);
nextResult.forEach(result.add,result);
}
if (result.size > 0) {
result.add(node.id);
}
delete stack[node.id];
return result;
}

function checkNode(node) {
if (node.getPreviousNodes(followLinkNodes).length === 0) {
// Nothing before this node - cannot be in a loop
return;
Expand All @@ -29,29 +54,15 @@ module.exports = {
// Nothing after this node - cannot be in a loop
return;
}
let level = 1;
let stack = [node]
let visited = {};
while(stack.length > 0) {
let n = stack.pop();
checked[n.id] = true;
if (!visited[n.id]) {
visited[n.id] = level++;
let next = n.getNextNodes(followLinkNodes);
next.forEach(nn => {
if (!visited[nn.id]) {
stack.push(nn);
}
else if (visited[nn.id] <=
visited[n.id]) {
context.report({
location: [n.id],
message: "loop detected"
});
}
});
}

const result = checkNodeGraph(node);
if (result.size > 0) {
context.report({
location: Array.from(result),
message: "loop detected"
});
}

}
return {
node: function(node) {
Expand Down

0 comments on commit f71dc9c

Please sign in to comment.