D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 23349 - Disallow assignments in ?: expressions
Summary: Disallow assignments in ?: expressions
Status: RESOLVED WONTFIX
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P1 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2022-09-20 14:42 UTC by Bolpat
Modified: 2022-09-23 09:13 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Bolpat 2022-09-20 14:42:46 UTC
Currently, conditional expressions (the formal name for the tenery operator `?:`) allow for an assignment in its then-part (between question mark and colon), but not its else-part (after colon). There’s even an example in the spec[1]:
    test ? a = b : (c = 2);
This is something compilers would warn about, and here, D’s no-warning policy is correct: Make it an error and require parentheses:
    test ? (a = b) : (c = 2);

In the grammar, it is a simple change:
From 
    ConditionalExpression:
        OrOrExpression
        OrOrExpression ? Expression : ConditionalExpression
to
    ConditionalExpression:
        OrOrExpression
        OrOrExpression ? ConditionalExpression : ConditionalExpression

Note: The only Expressions below ConditionalExpression are CommaExpression and AssignExpression.

[1]: https://dlang.org/spec/expression.html#conditional_expressions
Comment 1 RazvanN 2022-09-22 07:57:52 UTC
Why would we do this? The else-part is required to have parenthesis because of the ambiguity, but as far as I can see there is no way you could have an ambiguity for the assignment in the then-part.
Comment 2 Bolpat 2022-09-22 12:59:09 UTC
(In reply to RazvanN from comment #1)
> Why would we do this? The else-part is required to have parenthesis because
> of the ambiguity, but as far as I can see there is no way you could have an
> ambiguity for the assignment in the then-part.

It’s not about ambiguity, it’s about consistency.
Comment 3 RazvanN 2022-09-22 13:24:49 UTC
(In reply to Bolpat from comment #2)
> (In reply to RazvanN from comment #1)
> > Why would we do this? The else-part is required to have parenthesis because
> > of the ambiguity, but as far as I can see there is no way you could have an
> > ambiguity for the assignment in the then-part.
> 
> It’s not about ambiguity, it’s about consistency.

I don't see why we need to limit something just for the sake of consistency. The limitation on the then-part is put in place because of the possibility of ambiguous cases. Since the then-part is always unambiguous, no limitation is put in place. I find that the argument of consistency is not valid in this case. Therefore, my suggestion is to close this as "WONTFIX".