Skip to content

Commit

Permalink
fix: wrap postfix statements in parens when followed by a semicolon
Browse files Browse the repository at this point in the history
Fixes decaffeinate#748

`a if b; c` is a conditional followed by a statement, but `if b then a; c` has
`a; c` as the conditional body. To avoid this, we can always wrap these types of
statements in parens if there's a semicolon after them.
  • Loading branch information
alangpierce committed Apr 1, 2017
1 parent e50d0c7 commit 20a6a2f
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/utils/postfixNodeNeedsOuterParens.js
Expand Up @@ -7,12 +7,14 @@ import type NodePatcher from '../patchers/NodePatcher';
* Determine if the given postfix if/while/for needs to have parens wrapped
* around it while it is reordered. This happens when the expression has a comma
* after it as part of a list (function args, array initializer, or object
* initializer).
* initializer). It also happens when there is a semicolong immediately
* afterward, since without the parens the next statement would be pulled into
* the block.
*/
export default function postfixNodeNeedsOuterParens(patcher: NodePatcher): boolean {
let nextToken = patcher.nextToken();
if (nextToken) {
return nextToken.type === SourceType.COMMA;
return nextToken.type === SourceType.COMMA || nextToken.type === SourceType.SEMICOLON;
}
return false;
}
8 changes: 8 additions & 0 deletions test/conditional_test.js
Expand Up @@ -740,4 +740,12 @@ describe('conditionals', () => {
})()) { a; }
`);
});

it('handles a postfix conditional followed by a semicolon', () => {
check(`
a if b; c
`, `
(b ? a : undefined); c;
`);
});
});
8 changes: 8 additions & 0 deletions test/for_test.js
Expand Up @@ -1374,4 +1374,12 @@ describe('for loops', () => {
({a: (Array.from(c).map((b) => b)), d});
`);
});

it('properly converts a postfix for followed by a semicolon', () => {
check(`
foo = () -> null for i in []; t
`, `
let foo = function() { ([].map((i) => null)); return t; };
`);
});
});
14 changes: 14 additions & 0 deletions test/while_test.js
Expand Up @@ -431,4 +431,18 @@ describe('while', () => {
})()), d});
`);
});

it('handles a postfix while followed by a semicolon', () => {
check(`
a while b; c
`, `
((() => {
let result = [];
while (b) {
result.push(a);
}
return result;
})()); c;
`);
});
});

0 comments on commit 20a6a2f

Please sign in to comment.