[Issue 19916] union member access should be un- at safe

d-bugmail at puremagic.com d-bugmail at puremagic.com
Thu May 30 12:01:17 UTC 2019


https://issues.dlang.org/show_bug.cgi?id=19916

--- Comment #9 from Dennis <dkorpel at live.nl> ---
(In reply to Simen Kjaeraas from comment #8)
> Did you see my example code?

Yes, that's why I added "without using @trusted". @safe disallows
uninitialized/overlapping pointers, you explicitly circumvented that by casting
to an integer type and made it @trusted, and now it breaks. That means your
code couldn't be @trusted because you didn't account for overlap, not that
overlap of non-pointers is unsafe.

Your second version states:
// We know idx can only be set by the constructor
That's clearly false, that's even the point of the example. A logic bug causing
your @trusted code to break is not a violation of @safe. I'm a bit surprised
that with `@disable this();` void and union initialization is still allowed.
(n.b. you can also do `NotAPointer.init.callMethod();`). Arguably that is an
issue of @disable this.

To me the larger issue is that @trusted is too easily slapped on a function
without considering all the ways in which your code can be used. You can't
expect every programmer to check that their @trusted code is safe in every
imaginable setting / with every possible language feature, when even
experienced D programmers get it wrong. (See for example
https://github.com/atilaneves/automem/issues/25 or
https://issues.dlang.org/show_bug.cgi?id=19777). 

In theory, a trusted function should be memory safe any way you call it from
safe code. In practice, some trusted functions have oversights or make
assumptions about the call site / context, meaning that a function calling
@trusted code is also really @trusted instead of safe. 

Removing more and more things you can do from @safe code does not seem like a
good solution to me. What if I modify idx in your example? You can make it
private, but then the entire module is implicitly @trusted. In fact, the whole
project becomes @trusted because of __traits(getMember). Shall we make that not
@safe too?

--


More information about the Digitalmars-d-bugs mailing list