Skip to content

Commit

Permalink
fix: skip computed key when renaming (#16756)
Browse files Browse the repository at this point in the history
* fix

* review
  • Loading branch information
liuxingbaoyu authored Aug 21, 2024
1 parent 575863c commit 2b289fb
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 3 deletions.
23 changes: 20 additions & 3 deletions packages/babel-traverse/src/scope/lib/renamer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,15 +162,32 @@ export default class Renamer {
const blockToTraverse = process.env.BABEL_8_BREAKING
? scope.block
: (arguments[0] as t.Pattern | t.Scopable) || scope.block;

// When blockToTraverse is a SwitchStatement, the discriminant
// is not part of the current scope and thus should be skipped.

// const foo = {
// get [x]() {
// return x;
// },
// };
const skipKeys: Record<string, true> = { discriminant: true };
if (t.isMethod(blockToTraverse)) {
if (blockToTraverse.computed) {
skipKeys.key = true;
}
if (!t.isObjectMethod(blockToTraverse)) {
skipKeys.decorators = true;
}
}

traverseNode(
blockToTraverse,
explode(renameVisitor),
scope,
this,
scope.path,
// When blockToTraverse is a SwitchStatement, the discriminant
// is not part of the current scope and thus should be skipped.
{ discriminant: true },
skipKeys,
);

if (process.env.BABEL_8_BREAKING) {
Expand Down
81 changes: 81 additions & 0 deletions packages/babel-traverse/test/scope.js
Original file line number Diff line number Diff line change
Expand Up @@ -1137,6 +1137,87 @@ describe("scope", () => {
}"
`);
});

it(`computed key should not be renamed`, () => {
const program = getPath(`
let x = 1
const foo = {
get [x]() {
return x
},
}`);
program.traverse({
Function(path) {
const bodyPath = path.get("body");
// create a declaration that shadows parent variable
bodyPath.scope.push({
id: t.identifier("x"),
kind: "const",
init: t.nullLiteral(),
});
// rename the new "local" declaration
bodyPath.scope.rename("x", "y");
},
});
expect(program + "").toMatchInlineSnapshot(`
"let x = 1;
const foo = {
get [x]() {
const y = null;
return y;
}
};"
`);
});

it(`decorators should not be renamed`, () => {
const program = getPath(
`
let x;
class Foo {
@x
[x]() {
return x;
}
@x
#method() {
return x;
}
}`,
{
plugins: [["decorators"]],
},
);

program.traverse({
Function(path) {
const bodyPath = path.get("body");
// create a declaration that shadows parent variable
bodyPath.scope.push({
id: t.identifier("x"),
kind: "const",
init: t.nullLiteral(),
});
// rename the new "local" declaration
bodyPath.scope.rename("x", "y");
},
});
expect(program + "").toMatchInlineSnapshot(`
"let x;
class Foo {
@x
[x]() {
const y = null;
return y;
}
@x
#method() {
const y = null;
return y;
}
}"
`);
});
});

describe("constantViolations", () => {
Expand Down

0 comments on commit 2b289fb

Please sign in to comment.