Skip to content

Commit

Permalink
fix: improve variable declarator removal (#16587)
Browse files Browse the repository at this point in the history
* fix: fixed issue16583 + test

* modified getBinding to getOwnBinding (same scope)

* reverted babel-plugin-proposal-do-expressions back

* refactor: moved fix from scope/index.ts to path/removal.ts

* add fail test

* fix

* review

* Update packages/babel-traverse/test/fixtures/scope/remove-nested-let-path/plugin.js

Co-authored-by: Nicolò Ribaudo <hello@nicr.dev>

* review

* Update packages/babel-traverse/src/path/lib/removal-hooks.ts

---------

Co-authored-by: Babel Bot <30521560+liuxingbaoyu@users.noreply.github.com>
Co-authored-by: Nicolò Ribaudo <hello@nicr.dev>
  • Loading branch information
3 people authored Jul 27, 2024
1 parent 30b4473 commit 801d3cb
Show file tree
Hide file tree
Showing 9 changed files with 49 additions and 3 deletions.
7 changes: 4 additions & 3 deletions packages/babel-traverse/src/path/removal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,16 @@ export function remove(this: NodePath) {
_assertUnremoved.call(this);

this.resync();
if (!this.opts?.noScope) {
_removeFromScope.call(this);
}

if (_callRemovalHooks.call(this)) {
_markRemoved.call(this);
return;
}

if (!this.opts?.noScope) {
_removeFromScope.call(this);
}

this.shareCommentsWithSiblings();
_remove.call(this);
_markRemoved.call(this);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
let a = 33;
}
let a = 42;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"plugins": ["./plugin"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{}
let a = 42;
/*// a is defined when visiting a=33? true*/
/*// a is defined when visiting a=42? true*/
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module.exports = function ({ types }) {
return {
visitor: {
VariableDeclarator(path) {
const { value } = path.node.init;

if (value === 33) path.remove();

types.addComment(
path.scope.getProgramParent().path.node,
"trailing",
`// a is defined when visiting a=${value}? ${path.scope.hasBinding("a")}`
);
},
},
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
var a = 1;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"plugins": ["./plugin"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports = function () {
return {
visitor: {
VariableDeclarator(path) {
path.remove();
expect(path.scope.getBinding("a")).toBeUndefined();
},
},
};
};

0 comments on commit 801d3cb

Please sign in to comment.