Special case paren printing in for-loop init node

The printer doesn't have ancestry information so we have to set a flag before printing for's `node.init`.
We also need to make sure we're not printing extra parens so we check `node.needsParens` before adding them.
This commit is contained in:
Amjad Masad 2015-10-27 16:04:46 -07:00
parent 332bde6a0d
commit 6caaf68024
4 changed files with 20 additions and 1 deletions

View File

@ -1,5 +1,6 @@
import isInteger from "is-integer";
import isNumber from "lodash/lang/isNumber";
import n from "../node"
import * as t from "../../types";
/**
@ -220,10 +221,20 @@ export function AssignmentPattern(node, print) {
* Prints AssignmentExpression, prints left, operator, and right.
*/
export function AssignmentExpression(node, print) {
export function AssignmentExpression(node, print, parent) {
// Somewhere inside a for statement `init` node but doesn't usually
// needs a paren except for `in` expressions: `for (a in b ? a : b;;)`
var parens = this._inForStatementInit && node.operator === "in" &&
!n.needsParens(node, parent);
if (parens) {
this.push("(");
}
// todo: add cases where the spaces can be dropped when in compact mode
print.plain(node.left);
var spaces = node.operator === "in" || node.operator === "instanceof";
spaces = true; // todo: https://github.com/babel/babel/issues/1835
this.space(spaces);
@ -241,6 +252,10 @@ export function AssignmentExpression(node, print) {
this.space(spaces);
print.plain(node.right);
if (parens) {
this.push(")");
}
}
/**

View File

@ -41,7 +41,9 @@ export function ForStatement(node, print) {
this.keyword("for");
this.push("(");
this._inForStatementInit = true;
print.plain(node.init);
this._inForStatementInit = false;
this.push(";");
if (node.test) {

View File

@ -0,0 +1 @@
for ((a in b) ? a : b; i;);

View File

@ -0,0 +1 @@
for ((a in b) ? a : b; i;);