Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Transform scoping for for X in loop #16384

Merged
merged 2 commits into from Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 3 additions & 7 deletions packages/babel-plugin-transform-block-scoping/src/loop.ts
Expand Up @@ -239,17 +239,13 @@ export function wrapLoopBody(
varNames.push(...Object.keys(t.getBindingIdentifiers(decl.id)));
if (decl.init) {
assign.push(t.assignmentExpression("=", decl.id, decl.init));
} else if (t.isForXStatement(varPath.parent, { left: varPath.node })) {
assign.push(decl.id as t.Identifier);
}
}
if (assign.length > 0) {
let replacement: t.Node =
const replacement: t.Node =
assign.length === 1 ? assign[0] : t.sequenceExpression(assign);
if (
!t.isForStatement(varPath.parent, { init: varPath.node }) &&
!t.isForXStatement(varPath.parent, { left: varPath.node })
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you also add a test swapping the for ... in and for (;;) loops?

) {
replacement = t.expressionStatement(replacement);
}
varPath.replaceWith(replacement);
} else {
varPath.remove();
Expand Down
@@ -0,0 +1,17 @@
function w() {
for (let i = 0; i < y; i++) {
let outer = {}
for (var key in someObj) {
let x = () => outer;
}
}
}

function w2() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the difference between these two functions?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One is for in and the other is for of. :)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ohh I played the "find the difference between the two pictures" game for like 3 minutes before giving up 😬

for (let i = 0; i < y; i++) {
let outer = {}
for (var key of someObj) {
let x = () => outer;
}
}
}
@@ -0,0 +1,28 @@
function w() {
var _loop = function () {
var outer = {};
for (key in someObj) {
var x = function () {
return outer;
};
}
},
key;
for (var i = 0; i < y; i++) {
_loop();
}
}
function w2() {
var _loop2 = function () {
var outer = {};
for (key of someObj) {
var x = function () {
return outer;
};
}
},
key;
for (var i = 0; i < y; i++) {
_loop2();
}
}