Skip to content

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

Merged
czosel merged 1 commit into
prettier:mainfrom
Dextheking1:fix/nested-ternary-parens
Oct 19, 2026
Merged

czosel merged 1 commit into
prettier:mainfrom
Dextheking1:fix/nested-ternary-parens

Conversation

@Dextheking1

Copy link
Copy Markdown
Contributor

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

@czosel czosel left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks for contributing and sorry for the delay!

@czosel
czosel merged commit b7711d0 into prettier:main Oct 19, 2026
12 checks passed
@czosel

czosel commented Oct 19, 2026

Copy link
Copy Markdown
Collaborator

Released in v0.26.0 🎉

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

2 participants