Skip to content

Commit

Permalink
Add parenthesis around assignments (prettier#862)
Browse files Browse the repository at this point in the history
This is a neat trick from the React codebase. It helps highlight the fact that this is an assignment and not a comparison which is subtle to realize.

Fixes prettier#861
  • Loading branch information
vjeux authored and jlongster committed Mar 3, 2017
1 parent 205458a commit fa9dca3
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 11 deletions.
16 changes: 13 additions & 3 deletions src/fast-path.js
Original file line number Diff line number Diff line change
Expand Up @@ -407,11 +407,21 @@ FPp.needsParens = function(assumeExpressionContext) {
case "AssignmentExpression":
if (
parent.type === "ArrowFunctionExpression" &&
parent.body === node &&
node.left.type === "ObjectPattern"
parent.body === node
) {
return true;
return node.left.type === "ObjectPattern";
}
if (parent.type === "ForStatement" &&
(parent.init === node || parent.update === node)) {
return false;
}
if (parent.type === "ExpressionStatement") {
if (node.left.type === "ObjectPattern") {
return true;
}
return false;
}
return true;

case "ConditionalExpression":
switch (parent.type) {
Expand Down
4 changes: 2 additions & 2 deletions tests/flow/iter/__snapshots__/jsfmt.spec.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,12 @@ for (var j in b) {
}
var c;
for (var m in c = b) {
for (var m in (c = b)) {
foo(c[m]);
}
var d;
for (var n in d = a) {
for (var n in (d = a)) {
foo(d[n]); // d is a string, which shouldn't be used for array access
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,6 @@ var Bar = {
d: Foo.d(\\"bar\\") // no annotation required
};
module.exports = Foo, Bar;
(module.exports = Foo), Bar;
"
`;
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ var n = r(s) || 1;
(n: number);
var x = \\"\\";
if (x = r(s) || 1) {
if ((x = r(s) || 1)) {
(x: number);
}
Expand Down
8 changes: 4 additions & 4 deletions tests/flow/refinements/__snapshots__/jsfmt.spec.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ function bar2(x : Bar) {
function foo(x: ?number) {
var y;
if (y = x) {
if ((y = x)) {
var z = y * 1000;
}
}
Expand All @@ -49,22 +49,22 @@ type Bar = {
};
function bar0(x: Bar) {
while (x = x.parent) {
while ((x = x.parent)) {
// can't assign x to ?Bar
x.doStuff();
}
}
function bar1(x: ?Bar) {
while (x = x.parent) {
while ((x = x.parent)) {
// x.parent might be null
x.doStuff();
}
}
function bar2(x: Bar) {
var y = x;
while (y = y.parent) {
while ((y = y.parent)) {
y.doStuff();
}
}
Expand Down

0 comments on commit fa9dca3

Please sign in to comment.