Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

prevent infinite traversal when passed cyclic structures #107

Merged
merged 3 commits into from
Apr 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
`);
})
});