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

Closes https://github.com/benjamn/recast/issues/1357
This commit is contained in:
Brian Donovan 2023-08-10 07:03:13 -07:00
parent 2bb3a4ffdd
commit 068960405c
No known key found for this signature in database
2 changed files with 32 additions and 0 deletions

View file

@ -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":

View file

@ -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 = {",