Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(print): wrap unary exprs inside ** in parens #1361

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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