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

fix: avoid popContext on unvisited node paths #16305

Merged
merged 2 commits into from Feb 28, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 38 additions & 0 deletions packages/babel-traverse/test/traverse.js
Expand Up @@ -314,6 +314,44 @@ describe("traverse", function () {
["EXIT", "./Bar"],
]);
});
it("should preserve the context for those nodes that are not visited in sub-traversal", () => {
const code = `{ var first; function second() {} }`;
const ast = parse(code);
let contextLevel;
traverse(
ast,
{
enter(path) {
if (path.isFunctionDeclaration()) {
path.parentPath.traverse(
{
enter(path) {
if (path.isFunctionDeclaration()) {
path.parentPath.traverse(
{
enter(path) {
if (path.isVariableDeclaration()) path.stop();
},
},
{ level: 3 },
);
// the function declaration path should have state.level as 2
// as it is defined within level 2 traversal and the node is
// not visited in the next sub-traversal
contextLevel = path.state.level;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the main branch the contextLevel is 1, which is incorrect since Babel leaks the outer context to the inner sub-traversal.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

}
},
},
{ level: 2 },
);
}
},
},
undefined,
{ level: 1 },
);
expect(contextLevel).toBe(2);
});
});
describe("path.stop()", () => {
it("should stop the traversal when a grand child is stopped", () => {
Expand Down