Skip to content

Commit

Permalink
Initialize NodePath context when using getSibling (#12387)
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed Nov 23, 2020
1 parent 2b13863 commit 7d2a14b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/babel-traverse/src/path/family.js
Expand Up @@ -127,7 +127,7 @@ export function getSibling(key: string): NodePath {
container: this.container,
listKey: this.listKey,
key: key,
});
}).setContext(this.context);
}

export function getPrevSibling(): NodePath {
Expand Down
27 changes: 27 additions & 0 deletions packages/babel-traverse/test/family.js
@@ -1,5 +1,6 @@
import traverse from "../lib";
import { parse } from "@babel/parser";
import * as t from "@babel/types";

describe("path/family", function () {
describe("getBindingIdentifiers", function () {
Expand Down Expand Up @@ -81,6 +82,32 @@ describe("path/family", function () {
expect(sibling.getAllNextSiblings()).toHaveLength(2);
expect(lastSibling.getAllPrevSiblings()).toHaveLength(2);
});

it("should initialize path.scope when needed", function () {
const ast = parse("if (0) {}");

let testHasScope = false;
let consequentHasScope = false;

traverse(ast, {
IfStatement(path) {
// @babel/traverse pre-traverses the whole tree to populate the initial
// scope. Thus, it pre-caches paths for all the original nodes.
// We need to introduce two new nodes to avoid using the cached paths
// that already have the path.scope property.
path.set("test", t.identifier("a"));
path.set("consequent", t.expressionStatement(t.identifier("b")));

const testPath = path.get("test");

testHasScope = !!testPath.scope;
consequentHasScope = !!testPath.getSibling("consequent").scope;
},
});

expect(testHasScope).toBe(true);
expect(consequentHasScope).toBe(true);
});
});
});

Expand Down

0 comments on commit 7d2a14b

Please sign in to comment.