Skip to content

fix: keep parens around nested ternary in ?: - #2519

Open
Dextheking1 wants to merge 1 commit into
prettier:mainfrom
Dextheking1:fix/nested-ternary-parens
Open

Dextheking1 wants to merge 1 commit into
prettier:mainfrom
Dextheking1:fix/nested-ternary-parens

Conversation

@Dextheking1

Copy link
Copy Markdown

Formatting (1 ? 2 : 3) ?: 4 stripped the parentheses, producing 1 ? 2 : 3 ?: 4, which is a syntax error in PHP 8 (unparenthesized nested ternary).

src/needs-parens.mjs returned false for any retif node in the test position of a shorthand ternary (?:). It now returns true when the node is itself a full ternary (!!node.trueExpr), keeping the parens. Shorthand chains ($a ?: $b ?: $c) still format without parens since they associate to the left.

Added regression cases to tests/retif/retif.php; snapshot diff is purely additive. Full suite: 101 suites / 595 tests pass, plus AST_COMPARE=1 on the retif suite confirms the formatted output re-parses to an equivalent AST.

Closes #2115

Formatting `(1 ? 2 : 3) ?: 4` stripped the parentheses, producing
`1 ? 2 : 3 ?: 4`, which is a syntax error in PHP 8 (unparenthesized
nested ternary). needs-parens now keeps parens for a full ternary in the
test position of a shorthand ternary (`?:`). Shorthand chains still
format unparenthesized since they associate to the left.

Closes prettier#2115
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Parentheses around nested ternary expressions are removed, causing syntax error in PHP 8.0

1 participant