Bug 23349 – Disallow assignments in ?: expressions

Status
RESOLVED
Resolution
WONTFIX
Severity
enhancement
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2022-09-20T14:42:46Z
Last change time
2022-09-23T09:13:38Z
Assigned to
No Owner
Creator
Bolpat

Comments

Comment #0 by qs.il.paperinik — 2022-09-20T14:42:46Z
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 by razvan.nitu1305 — 2022-09-22T07:57:52Z
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 by qs.il.paperinik — 2022-09-22T12:59:09Z
(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 by razvan.nitu1305 — 2022-09-22T13:24:49Z
(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".