Allow redeclaration of loop variable in body (#11088)

This commit is contained in:
Daryl Tan 2020-02-11 17:19:03 +08:00 committed by GitHub
parent 865d5155c2
commit 3907396bd8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 83 additions and 4 deletions

View File

@ -19,7 +19,7 @@ export default declare((api, options) => {
visitor: {
ForOfStatement(path) {
const { scope } = path;
const { left, right, body, await: isAwait } = path.node;
const { left, right, await: isAwait } = path.node;
if (isAwait) {
return;
}
@ -48,8 +48,19 @@ export default declare((api, options) => {
);
}
const block = t.toBlock(body);
block.body.unshift(assignment);
let blockBody;
const body = path.get("body");
if (
body.isBlockStatement() &&
Object.keys(path.getBindingIdentifiers()).some(id =>
body.scope.hasOwnBinding(id),
)
) {
blockBody = t.blockStatement([assignment, body.node]);
} else {
blockBody = t.toBlock(body.node);
blockBody.body.unshift(assignment);
}
path.replaceWith(
t.forStatement(
@ -60,7 +71,7 @@ export default declare((api, options) => {
t.memberExpression(t.cloneNode(array), t.identifier("length")),
),
t.updateExpression("++", t.cloneNode(i)),
block,
blockBody,
),
);
},

View File

@ -0,0 +1,5 @@
for (const [head, ...tail] of array) {
const head = 1;
console.log(tail);
console.log(head);
}

View File

@ -0,0 +1,8 @@
for (let _i = 0, _array = array; _i < _array.length; _i++) {
const [head, ...tail] = _array[_i];
{
const head = 1;
console.log(tail);
console.log(head);
}
}

View File

@ -0,0 +1,5 @@
for (const [type, ...rest] of array) {
const type = 1;
console.log(rest);
console.log(type);
}

View File

@ -0,0 +1,8 @@
for (let _i = 0, _array = array; _i < _array.length; _i++) {
const [type, ...rest] = _array[_i];
{
const type = 1;
console.log(rest);
console.log(type);
}
}

View File

@ -0,0 +1,6 @@
for (const [head, ...tail] of array) {
const head = 1;
let tail;
console.log(tail);
console.log(head);
}

View File

@ -0,0 +1,9 @@
for (let _i = 0, _array = array; _i < _array.length; _i++) {
const [head, ...tail] = _array[_i];
{
const head = 1;
let tail;
console.log(tail);
console.log(head);
}
}

View File

@ -0,0 +1,6 @@
for (const {type, ...rest} of array) {
const type = 1;
let rest;
console.log(rest);
console.log(type);
}

View File

@ -0,0 +1,12 @@
for (let _i = 0, _array = array; _i < _array.length; _i++) {
const {
type,
...rest
} = _array[_i];
{
const type = 1;
let rest;
console.log(rest);
console.log(type);
}
}

View File

@ -0,0 +1,3 @@
for (const elm of array) {
const elm = 2;
}

View File

@ -0,0 +1,6 @@
for (let _i = 0, _array = array; _i < _array.length; _i++) {
const elm = _array[_i];
{
const elm = 2;
}
}