Casting in Safe D

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Nov 30 00:16:51 PST 2014


On Saturday, November 29, 2014 14:34:06 Nordlöw via Digitalmars-d-learn wrote:
> So what about forbidding this in nothrow functions? My vision
> with D is to be able to get more guarantees about stability than
> all other imperative languages. If the compiler cannot prove that
> alignments and memory regions match then a safe nothrow function
> doing these casts should IMO fail at compile time.

Forbidding what exactly? Your original post involves an Error being thrown
(which doesn't violate nothrow, because nothrow is for Exceptions, whereas
Errors don't), and there's nothing about that that violates @safety. The
operation being attempted is invalid, so an Error is thrown, ensuring that
the operation does not corrupt memory. The same goes for stuff like array
bounds checking on indexing. Errors are normally used in
cases where what's being done is invalid but can't be detected at compile
time, in which case, there's no way that you'd be able to get a compilation
error instead. With regards to array cast misalignment, I don't know. My
guess is that it's because it doesn't know what the actual underlying type
of the void[] array is. For instance, if you change it to

void[] void_array = new short[3];

then no Error gets thrown. In this basic example, flow analysis could detect
the actual type of the array, but dmd almost never does flow analysis, and
as soon as void_array is initialized by something opaque like the return
value of a function, then the compiler has no way of detecting the alignment
mismatch, and we're forced to have the runtime detect it. So, while I can
see why a compilation error would be desirable in this case, it doesn't
surprise me that there isn't one. And regardless, it doesn't violate @safe,
because having an Error thrown ensures that the operation that would be
unsafe never actually takes place.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list