8000 Initialize NodePath context when using `getSibling` (#12387) · babel/babel@7d2a14b · GitHub
[go: up one dir, main page]

Skip to content

Commit 7d2a14b

Browse files
Initialize NodePath context when using getSibling (#12387)
1 parent 2b13863 commit 7d2a14b

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

packages/babel-traverse/src/path/family.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ export function getSibling(key: string): NodePath {
127127
container: this.container,
128128
listKey: this.listKey,
129129
key: key,
130-
});
130+
}).setContext(this.context);
131131
}
132132

133133
export function getPrevSibling(): NodePath {

packages/babel-traverse/test/family.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import traverse from "../lib";
22
import { parse } from "@babel/parser";
3+
import * as t from "@babel/types";
34

45
describe("path/family", function () {
56
describe("getBindingIdentifiers", function () {
@@ -81,6 +82,32 @@ describe("path/family", function () {
8182
expect(sibling.getAllNextSiblings()).toHaveLength(2);
8283
expect(lastSibling.getAllPrevSiblings()).toHaveLength(2);
8384
});
85+
86+
it("should initialize path.scope when needed", function () {
87+
const ast = parse("if (0) {}");
88+
89+
let testHasScope = false;
90+
let consequentHasScope = false;
91+
92+
traverse(ast, {
93+
IfStatement(path) {
94+
// @babel/traverse pre-traverses the whole tree to populate the initial
95+
// scope. Thus, it pre-caches paths for all the original nodes.
96+
// We need to introduce two new nodes to avoid using the cached paths
97+
// that already have the path.scope property.
98+
path.set("test", t.identifier("a"));
99+
path.set("consequent", t.expressionStatement(t.identifier("b")));
100+
101+
const testPath = path.get("test");
102+
103+
testHasScope = !!testPath.scope;
104+
consequentHasScope = !!testPath.getSibling("consequent").scope;
105+
},
106+
});
107+
108+
expect(testHasScope).toBe(true);
109+
expect(consequentHasScope).toBe(true);
110+
});
84111
});
85112
});
86113

0 commit comments

Comments
 (0)
0