Skip to content

Commit

Permalink
prevent infinite traversal when passed cyclic structures (#107)
Browse files Browse the repository at this point in the history
Co-authored-by: 郑翔 <[email protected]>
Co-authored-by: Michael Ficarra <[email protected]>
  • Loading branch information
3 people authored Apr 15, 2020
1 parent e331050 commit 91489e6
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
18 changes: 18 additions & 0 deletions estraverse.js
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,15 @@
function isProperty(nodeType, key) {
return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;
}

function candidateExistsInLeaveList(leavelist, candidate) {
for (var i = leavelist.length - 1; i >= 0; --i) {
if (leavelist[i].node === candidate) {
return true;
}
}
return false;
}

Controller.prototype.traverse = function traverse(root, visitor) {
var worklist,
Expand Down Expand Up @@ -469,6 +478,11 @@
if (!candidate[current2]) {
continue;
}

if (candidateExistsInLeaveList(leavelist, candidate[current2])) {
continue;
}

if (isProperty(nodeType, candidates[current])) {
element = new Element(candidate[current2], [key, current2], 'Property', null);
} else if (isNode(candidate[current2])) {
Expand All @@ -479,6 +493,10 @@
worklist.push(element);
}
} else if (isNode(candidate)) {
if (candidateExistsInLeaveList(leavelist, candidate)) {
continue;
}

worklist.push(new Element(candidate, key, null, null));
}
}
Expand Down
24 changes: 24 additions & 0 deletions test/traverse.js
Original file line number Diff line number Diff line change
Expand Up @@ -559,4 +559,28 @@ describe('no listed keys fallback', function() {
() => traverse(tree, { enter(node) {} })
).to.throw('Unknown node type XXXExpression.');
});

it('break loop', function () {
const children = {
type: 'Children',
name: 'div'
};

const parent = {
type: 'Parent',
name: children,
parent: null,
};

children.parent = parent;

const tree = parent;

checkDump(Dumper.dump(tree, null, 'iteration'), `
enter - Parent
enter - Children
leave - Children
leave - Parent
`);
})
});

0 comments on commit 91489e6

Please sign in to comment.