Skip to content

Commit

Permalink
Code for fix from benjamn#1257
Browse files Browse the repository at this point in the history
  • Loading branch information
petergok committed May 17, 2023
1 parent 34a6b3d commit 6922345
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
8 changes: 8 additions & 0 deletions lib/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,12 @@ export interface Options extends DeprecatedOptions {
* @default true
*/
tokens?: boolean;

/**
* Whether to add parens around statements when possible while printing the AST.
* @default false
*/
avoidParens?: boolean;
}

interface DeprecatedOptions {
Expand Down Expand Up @@ -184,6 +190,7 @@ const defaults: Options = {
arrowParensAlways: false,
flowObjectCommas: true,
tokens: true,
avoidParens: false,
};
const hasOwn = defaults.hasOwnProperty;

Expand Down Expand Up @@ -219,5 +226,6 @@ export function normalize(opts?: Options): NormalizedOptions {
arrowParensAlways: get("arrowParensAlways"),
flowObjectCommas: get("flowObjectCommas"),
tokens: !!get("tokens"),
avoidParens: !!get("avoidParens"),
};
}
2 changes: 1 addition & 1 deletion lib/printer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ function genericPrint(path: any, config: any, options: any, printPath: any) {
if (decoratorsLines.isEmpty()) {
// Nodes with decorators can't have parentheses, so we can avoid
// computing path.needsParens() except in this case.
if (!options.avoidRootParens) {
if (!options.avoidRootParens && !config.avoidParens) {
shouldAddParens = path.needsParens();
}
} else {
Expand Down
28 changes: 28 additions & 0 deletions test/printer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2565,4 +2565,32 @@ describe("printer", function () {
),
);
});

const withoutParens = [
"async function add(a, b) {",
" const z = foo || await getFoo();",
" return z;",
"}"
].join(eol);

const withParens = [
"async function add(a, b) {",
" const z = foo || (await getFoo());",
" return z;",
"}"
].join(eol);

it("With & without parens added to reprinted code", function () {
const ast = parse(withoutParens);
let printer = new Printer({ tabWidth: 2 });

const withParensPrinted = printer.print(ast).code; // Default behaviour
assert.strictEqual(typeof withParensPrinted, "string");
assert.strictEqual(withParensPrinted, withParens);

printer = new Printer({ tabWidth: 2, avoidParens: true });
const reprinted = printer.print(ast).code;
assert.strictEqual(typeof reprinted, "string");
assert.strictEqual(reprinted, withoutParens);
});
});

0 comments on commit 6922345

Please sign in to comment.