Skip to content

Commit

Permalink
Register switch's discriminant in the outer scope (#15167)
Browse files Browse the repository at this point in the history
* Add failing test

* Register `switch`'s `discriminant` in the outer scope
  • Loading branch information
nicolo-ribaudo committed Nov 9, 2022
1 parent 7ed57c0 commit 7272f23
Show file tree
Hide file tree
Showing 6 changed files with 29 additions and 3 deletions.
@@ -0,0 +1,3 @@
switch (x) {
default: let x;
}
@@ -0,0 +1,4 @@
switch (x) {
default:
var _x;
}
@@ -0,0 +1,4 @@
let x;
switch (x) {
default: let x;
}
@@ -0,0 +1,5 @@
var x;
switch (x) {
default:
var _x;
}
8 changes: 5 additions & 3 deletions packages/babel-traverse/src/path/context.ts
Expand Up @@ -133,10 +133,12 @@ export function setScope(this: NodePath) {

let path = this.parentPath;

// Skip method scope if is computed method key or decorator expression
if (
(this.key === "key" || this.listKey === "decorators") &&
path.isMethod()
// Skip method scope if is computed method key or decorator expression
((this.key === "key" || this.listKey === "decorators") &&
path.isMethod()) ||
// Skip switch scope if for discriminant (`x` in `switch (x) {}`).
(this.key === "discriminant" && path.isSwitchStatement())
) {
path = path.parentPath;
}
Expand Down
8 changes: 8 additions & 0 deletions packages/babel-traverse/test/scope.js
Expand Up @@ -282,6 +282,14 @@ describe("scope", () => {
});
});

it("switch discriminant scope", () => {
expect(
getPath(`let a = "outside"; switch (a) { default: let a = "inside" }`)
.get("body.1.discriminant")
.scope.getBinding("a").path.node.init.value,
).toBe("outside");
});

it("variable declaration", function () {
expect(getPath("var foo = null;").scope.getBinding("foo").path.type).toBe(
"VariableDeclarator",
Expand Down

0 comments on commit 7272f23

Please sign in to comment.