Bug 21783 – Add `if` as an operator

Status
NEW
Severity
enhancement
Priority
P4
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2021-03-29T15:54:28Z
Last change time
2024-12-13T19:15:39Z
Assigned to
No Owner
Creator
Bolpat
Moved to GitHub: dmd#18030 →

Comments

Comment #0 by qs.il.paperinik — 2021-03-29T15:54:28Z
Make `if` a binary infix operator on the same precedence level as the trinary operator. Its semantics would be: (lhs if rhs) is lowered to (!(rhs) || lhs). The big win is when stating invariants or preconditions and especially post-conditions. IMO, those should be easy to understand for the common programmer. The alternatives are just bad as they aren't grasped as an implication (usually, one goes the route over the rewrite above). The best I could come up with is lhs ? rhs : true which at least uses something that is recognized as an implication. As an example, this could be the contracted version of a divMod implementation: void divMod(int a, int b, int q, int r) in (b > 0) out (; q <= 0 if a < 0) out (; q >= 0 if a > 0) out (; r <= 0 if a < 0) out (; r >= 0 if a > 0) { ... } I find it really hard to formulate these in a comprehensive manner without an `if` operator.
Comment #1 by qs.il.paperinik — 2021-03-29T15:58:21Z
It should have read: > The best I could come up with is > > rhs ? lhs : true > > which [...]
Comment #2 by dfj1esp02 — 2021-03-30T14:15:08Z
bool conditional(bool c, bool check) { return c?check:true; } void divMod(int a, int b, int q, int r) in (b > 0) out (; conditional(a < 0, q <= 0)) out (; conditional(a > 0, q >= 0)) out (; conditional(a < 0, r <= 0)) out (; conditional(a > 0, r >= 0))
Comment #3 by qs.il.paperinik — 2021-03-31T00:57:39Z
Unless `conditional` is part of object.d, it needs to be defined or imported which is a bummer for pre- and post-conditions. Also, it's not immediately clear what it means.
Comment #4 by robert.schadek — 2024-12-13T19:15:39Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dmd/issues/18030 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB