Fix `in` inside of a for in a nested way (#954)

Fixes #907
master
Christopher Chedeau 2017-03-08 17:09:37 -08:00 committed by GitHub
parent 24c314da01
commit c2aacae54c
3 changed files with 62 additions and 9 deletions

View File

@ -1,3 +1,5 @@
"use strict";
var assert = require("assert");
var types = require("ast-types");
var util = require("./util");
@ -280,15 +282,21 @@ FPp.needsParens = function(assumeExpressionContext) {
}
case "BinaryExpression":
// TODO https://github.com/prettier/prettier/issues/907 this is not complete
if (
node.operator === "in" &&
parent.type === "ForStatement" &&
parent.init === node
) {
return true;
}
if (node.operator === "in" && parent.type === "AssignmentExpression") {
const isLeftOfAForStatement = node => {
let i = 0;
while (node) {
let parent = this.getParentNode(i++);
if (!parent) {
return false;
}
if (parent.type === "ForStatement" && parent.init === node) {
return true;
}
node = parent;
}
return false;
};
if (node.operator === "in" && isLeftOfAForStatement(node)) {
return true;
}
// else fall through

View File

@ -25,22 +25,58 @@ for (var i = 0; i < 10; ++i) {
exports[`in.js 1`] = `
"for ((x in a);;) {}
for (a=(a in b);;) {}
for (let a = (b in c); ; );
for (a && (b in c); ; );
for (a => (b in c); ; );
function* g() {
for (yield (a in b); ; );
}
async function f() {
for (await (a in b); ; );
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for ((x in a); ; ) {
}
for (a = (a in b); ; ) {
}
for (let a = (b in c); ; );
for (a && (b in c); ; );
for (a => (b in c); ; );
function* g() {
for (yield (a in b); ; );
}
async function f() {
for (await (a in b); ; );
}
"
`;
exports[`in.js 2`] = `
"for ((x in a);;) {}
for (a=(a in b);;) {}
for (let a = (b in c); ; );
for (a && (b in c); ; );
for (a => (b in c); ; );
function* g() {
for (yield (a in b); ; );
}
async function f() {
for (await (a in b); ; );
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for ((x in a); ; ) {
}
for (a = (a in b); ; ) {
}
for (let a = (b in c); ; );
for (a && (b in c); ; );
for (a => (b in c); ; );
function* g() {
for (yield (a in b); ; );
}
async function f() {
for (await (a in b); ; );
}
"
`;

View File

@ -1,2 +1,11 @@
for ((x in a);;) {}
for (a=(a in b);;) {}
for (let a = (b in c); ; );
for (a && (b in c); ; );
for (a => (b in c); ; );
function* g() {
for (yield (a in b); ; );
}
async function f() {
for (await (a in b); ; );
}