On Thursday, 27 March 2025 at 00:26:27 UTC, Andrey Zherikov wrote:
> See wiki for details.
Proposed syntax:
A ?: B
This is equivalent to:
auto R = A; // temporary (hidden) variable
(cast(bool) R) ? R : B;
Semantics: return A
if it's truthy, or B
otherwise.
Benefit: avoids evaluating if A
twice which might be a call to some function with side effects.
The lowering is actually tricky because the right-hand side ought to be evaluated only if the left-hand side is false
as a condition. Proposing a lowering of an expression to a statement is making things difficult.
The best lowering I could come up with is:
lhs ?: rhs
// to
(auto ref (auto ref __lhs) => __lhs ? __lhs : rhs)(lhs)
The right-hand side can be placed in the lambda as-is because it only occurs once and in fact has to be put there because passing it as a parameter evaluates it prematurely. The left-hand side must be evaluated first.
The auto ref
is needed to enable (l ?: r) = x
. It would be surprising if that didn’t work if both l
and r
are rvalues since (l ? l : r) = x
does work.
Lastly, the cast(bool)
is incorrect: An explicit cast to bool triggers opCast
if present, which is something you don’t want in general, e.g. when you have a class with opCast
and an object c
, then if (c)
performs a nullity check, whereas if (cast(bool) c)
lowers to if (c.opCast!bool)
and that does whatever it does, but certainly doesn’t check for null, but assumes it’s not null.
Bottom line is, such a trivial lowering is an enhancement issue, but needs no DIP. There are virtually no surprises to be expected, no weird issues, and that is obvious; it’s just a matter of opinion if the addition provides enough value to the language and maybe its syntax (because ??
is a contender). That discussion is simply too minor to warrant a DIP. Given how many languages with similar syntax have it, it’s likely the assessment is that it does provide enough value.