Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

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