diff --git a/lib/options.ts b/lib/options.ts index c545b389..d58ff724 100644 --- a/lib/options.ts +++ b/lib/options.ts @@ -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 { @@ -184,6 +190,7 @@ const defaults: Options = { arrowParensAlways: false, flowObjectCommas: true, tokens: true, + avoidParens: false, }; const hasOwn = defaults.hasOwnProperty; @@ -219,5 +226,6 @@ export function normalize(opts?: Options): NormalizedOptions { arrowParensAlways: get("arrowParensAlways"), flowObjectCommas: get("flowObjectCommas"), tokens: !!get("tokens"), + avoidParens: !!get("avoidParens"), }; } diff --git a/lib/printer.ts b/lib/printer.ts index 008e7e93..71c097f5 100644 --- a/lib/printer.ts +++ b/lib/printer.ts @@ -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 { diff --git a/test/printer.ts b/test/printer.ts index a0fc12f9..bb2e1002 100644 --- a/test/printer.ts +++ b/test/printer.ts @@ -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); + }); });