Skip to content

Commit

Permalink
Merge branch 'fix/unary-expression-parens' (benjamn#922)
Browse files Browse the repository at this point in the history
  • Loading branch information
coderaiser committed May 14, 2021
2 parents 9f40c9c + ed6aeec commit 606496a
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
10 changes: 7 additions & 3 deletions lib/printer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -963,13 +963,17 @@ function genericPrintNoParens(path: any, options: any, print: any) {
// Literal identifying the imported-from module.
return fromString(nodeStr(n.value, options), options);

case "UnaryExpression":
case "UnaryExpression": {
parts.push(n.operator);
const {argument} = path.getValue();
const needsParens = argument.type === 'LogicalExpression';
const parenLeft = needsParens ? '(' : '';
const parenRight = needsParens ? ')' : '';
if (/[a-z]$/.test(n.operator)) parts.push(" ");
parts.push(path.call(print, "argument"));
parts.push(parenLeft, path.call(print, "argument"), parenRight);
return concat(parts);

case "UpdateExpression":
} case "UpdateExpression":
parts.push(path.call(print, "argument"), n.operator);

if (n.prefix) parts.reverse();
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@
"tslib": "^2.0.1"
},
"devDependencies": {
"@babel/core": "7.11.6",
"@babel/parser": "^7.12.5",
"@babel/core": "^7.11.6",
"@babel/parser": "^7.11.5",
"@babel/preset-env": "7.11.5",
"@types/esprima": "4.0.2",
"@types/glob": "7.1.3",
Expand Down
12 changes: 12 additions & 0 deletions test/babel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -502,4 +502,16 @@ describe("Babel", function () {
["class A {", " declare public readonly x;", "}"].join(eol),
);
});

it("should keep braces in !(a && b)", function () {
const code = '(options || !options.bidirectional) ? false : true;';
const ast = recast.parse(code, parseOptions);

ast.program.body[0].expression = b.unaryExpression('!', ast.program.body[0].expression.test);

assert.strictEqual(
recast.print(ast).code,
'!(options || !options.bidirectional);',
);
});
});

0 comments on commit 606496a

Please sign in to comment.