Open 0xba1 opened 2 years ago
There are grammar ambiguities with prefix operators (really just -
), where {a?-b:c}
can be either a map literal ({(a ?- b) : c}
) or a set literal ({a ? (-b) : c}
).
We can disambiguate by making ?-
a single token, so it's always going to be the map literal above. That's a breaking change, but one which only affects unformatted code (formatted code will always have a space between ?
and -
).
With that, ?op
where op
is an infix operator can definitely mean null
if either operand is null, and op
if both are non-null
.
It would mean that the static behavior of e1 ?+ e2
would be:
T1
be the static type of e1
with no context type.S1
be NON_NULL(T1
)+
be the plus operator method defined on S1
(either interface or applicable extension method), with function signature R Function(P)
.T2
be the static type of e2
with P?
as context type.T1
nor T2
is nullable.S2
be NON_NULL(T2
)S2
is not assignable to P
.e1 ?+ e2
is R?
.The runtime behavior would be:
e1
to a value v1
.v1
is null
then e1 ?+ e2
evaluates to null
.e2
to a value v2
v2
is null
then e1 ?+ e2
evaluates to null
.+
operator of S1
on v1
with v2
as argument, let v3
be the value it returns.e1 ?+ e2
is v3
.Basically, it's short for (let v1 = e1 in v1 == null ? null : (let v2 = e2 in v2 == null ? null : v1 + v2))
.
(I chose to short-circuit e2
evaluation here because ?.
and ?[]
both short-circuit what's after the ?
, so it would be consistent to do it here too. It's not necessary.)
Could also work for x?++
and x ?+= 1
.
Especially for integer and double arithmetic, it seems unnecessary to check if a value is null every time one needs to add or subtract. I propose we make more null aware operators that check if either value is null, and returns null if true but returns the result of the normal operation if false.