Skip to content

Commit

Permalink
Merge pull request #1361 from benjamn/fix/enclose-unary-expression-in…
Browse files Browse the repository at this point in the history
…side-exponentiation-in-parens

fix(print): wrap unary exprs inside `**` in parens
  • Loading branch information
eventualbuddha committed Aug 11, 2023
2 parents 2bb3a4f + 0689604 commit 97af13f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/fast-path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,17 @@ FPp.needsParens = function (assumeExpressionContext) {

if (!parent) return false;

// Wrap e.g. `-1` in parentheses inside `(-1) ** 2`.
if (
node.type === "UnaryExpression" &&
parent.type === "BinaryExpression" &&
name === "left" &&
parent.left === node &&
parent.operator === "**"
) {
return true;
}

switch (node.type) {
case "UnaryExpression":
case "SpreadElement":
Expand Down
21 changes: 21 additions & 0 deletions test/printer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2031,6 +2031,27 @@ describe("printer", function () {
assert.strictEqual(pretty, code);
});

for (const operator of ["-", "+", "~", "!", "typeof", "void"] as const) {
it(`adds parenthesis around '${operator}' unary expression in exponentiation expression`, function () {
const code = `(${
/[a-z]/.test(operator) ? `${operator} ` : operator
}a) ** 2;`;
const ast = b.program([
b.expressionStatement(
b.binaryExpression(
"**",
b.unaryExpression(operator, b.identifier("a"), true),
b.literal(2),
),
),
]);

const printer = new Printer();
const pretty = printer.print(ast).code;
assert.strictEqual(pretty, code);
});
}

it("prints flow object type internal slots correctly", function () {
const code = [
"type MyObjectType = {",
Expand Down

0 comments on commit 97af13f

Please sign in to comment.