February 25, 2016
From the thread about Kotlin and null safety:
http://forum.dlang.org/post/yxfdycdtgdesbsozvhdb@forum.dlang.org

On Tuesday, 23 February 2016 at 06:49:46 UTC, Tobias Müller wrote:
> rsw0x <anonymous@anonymous.com> wrote:
>> D has this too, but only for nullable types afaik.
>> 
>> if(byte* ptr = someFunc()){
>> //...
>> }
>
> That's not quite the same as there are no non-nullable pointers in D.
> There's no guarantee from the type system that the byte* is not null and
> there are no compiler checks involved.
> It's a simple runtime check.
>
> OTOH in the examples in Kotlin/Rust the variable 'var' changes its type
> from 'int?' to plain 'int'.
> In Kotlin this is done with static analysis, in Rust with rebinding of the
> name.

Inspired a bit by Swift's guard statement, maybe we could have a __guard statement - similar but a bit different. It is used to conditionally define a new variable of wrapped type such as Adam D Ruppe's NotNull, see:

http://forum.dlang.org/post/yxfdycdtgdesbsozvhdb@forum.dlang.org

But it should be useable for other types representing runtime guarantees too.

T* ptr = ...;

__guard(NonNull, p = ptr){
	// typeof(p) is NonNull!T
}

__guard(NonNull, ptr){
	// existing ptr is shadowed by ptr variable of type NonNull!T
}

__guard(NonNull, ptr) else return;
// existing ptr is shadowed by ptr variable of type NonNull!T

Note the last __guard else statement form allows no {} body before else. The else clause must prevent execution from proceeding past the __guard statement.

These statements should be easy to implement in the compiler as they can just forward to static struct methods, opGuard and opGuardWrap. NonNull!T.opGuard takes ptr and returns a boolean. NonNull!T.opGuardWrap returns the wrapped ptr as NonNull!T (without checking if ptr is null again).

Having a __guard statement is a simple way to mimic types becoming more constrained following a runtime check. It doesn't complicate the type system or need special analysis from the compiler. Thoughts?