Is there a way to configure parenthesizerRules?

19 Views Asked by At

I am using the typescript compiler API to build typescript from scratch.

I have encountered an issue where ts.factory.createBinaryExpression results in parenthesis being added when multiple logical and statements are chained together.

This seems to be based on the parenthesizerRules, specifically this line (in typescript.ts) and some sub calls:

node.right = parenthesizerRules().parenthesizeRightSideOfBinary(operatorKind, node.left, right);

Example code as follows:

import ts from 'typescript'

const printNodes = (node: ts.Node): string => {
    const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed, omitTrailingSemicolon: true });
    return printer.printNode(ts.EmitHint.Unspecified, node, ts.createSourceFile("file.ts", "", ts.ScriptTarget.Latest, /*setParentNodes*/ false, ts.ScriptKind.TS))
}

const x = ts.factory.createIdentifier("x")
const y = ts.factory.createIdentifier("y")
const binary = ts.factory.createBinaryExpression(
    x,
    ts.SyntaxKind.LessThanToken,
    y
)

// binary expression: x < y
console.log(`binary expression: ${printNodes(binary)}`)

const logical_and = ts.factory.createBinaryExpression(binary, ts.SyntaxKind.AmpersandAmpersandToken,
    ts.factory.createBinaryExpression(
    x, ts.SyntaxKind.LessThanToken, ts.factory.createNumericLiteral(10))
)

// logical_and: x < y && x < 10
console.log(`logical_and: ${printNodes(logical_and)}`)

const logical_and_and = ts.factory.createBinaryExpression(binary, ts.SyntaxKind.AmpersandAmpersandToken, logical_and)
// logical_and_and: x < y && (x < y && x < 10)
console.log(`logical_and_and: ${printNodes(logical_and_and)}`)

The output I require is

x < y && x < y && x < 10

The code in typescript.js seems to be performing operator precedence comparisons to determine whether parenthesis are required.

I am importing code from another language, so I need to copy the exact logic. The situation above seems OK for &&, but once a few ||s are mixed in, things stop working as intended.

typescript version: 5.3.3

0

There are 0 best solutions below