Null-checked reference types
Richard (Rikki) Andrew Cattermole
richard at cattermole.co.nz
Wed Aug 7 01:39:29 UTC 2024
Lots here to talk about.
> Add the following type suffixes to the language: ? and !.
I'll ignore the syntax since that is already covered.
> Add operators for null-respecting access: ?., ?(…) (call if not
null), ?[…] (index if not null), ?= (assign if null).
This should be split out into a separate DIP. They are things I already
want for similar reasons.
However, they must decompose to loads and stores inside if statements.
This makes it temporally safe.
``var1.var2?.field = 2;``
```d
if (auto var2 = var1.var2) {
var2.field = 2;
}
```
This allows you to do both loads and stores and do something if it
failed transitively.
```d
if (var1.var2?.var3?.field = 3) {
// success
} else {
// failure
}
```
> No data flow analysis is proposed. Null checking is local and done by
tracking ? and ! by the type system.
DFA is only required if you want the type state to change as the
function is interpreted. So that's fine. That is a me thing to figure out.
However, you do not need to annotate function body variables with this
approach.
Look at the initializer of a function variable declaration, it'll tell
you if it has the non-null type state.
```d
int* ptr1;
int* ptr2 = ptr1;
```
Function parameters, (including return and this) need to be annotateable
with their type state.
```d
int* func(?nonnull return, ?nonnull this, ?nonnull int* ptr) {
return ptr;
}
```
They can also be inferred by first usage.
```d
void func(int* ptr) {
int v = *ptr;
}
```
Clearly ``ptr`` has the type state non-null.
However the problem which caused me some problems in the past is on
tracking variables outside of a function. You cannot do it.
Variables outside a function change type state during their lifespan.
They have the full life cycle, starting at reachable, into non-null and
then back to reachable. If you tried to force it to be non-null, the
language would force you to have an .init value that is non-null. This
is an known issue with classes already. It WILL produce logic errors
that are undetectable.
More information about the dip.development
mailing list