Will D always have a way to rebind an arbitrary data type?

Paul Backus snarwin at gmail.com
Mon Sep 27 20:55:56 UTC 2021


On Monday, 20 September 2021 at 08:43:48 UTC, FeepingCreature 
wrote:
> I'm trying to get a utility type `HeadMutable` merged in an 
> internal utility library,
> and one of the points of criticism in review is that the 
> mechanism I'm using (Turducken, if you remember 
> https://forum.dlang.org/thread/ekbxqxhnttihkoszzvxl@forum.dlang.org ) is extremely hacky; even though all parts of it are probably technically deliberately added to the language, it seems they add up to a pretty evil backdoor in the type system.

And indeed `Turducken` as presented in that post is unsound, 
since it allows `@safe` code to observe mutation of `immutable` 
data:

     void main() @safe
     {
         Turducken!(immutable(int)) td;
         td.bind(123);
         (ref immutable(int) value) {
             assert(value == 123);
             td.bind(456);
             assert(value == 123); // kaboom
         }(td.value);
     }

(Runnable: https://run.dlang.io/is/xCjYIz)

Because D does not have any notion of exclusive references (like 
Rust's `&mut`), the container has to assume that when `bind` is 
called, there may be outstanding references to the contained 
value. Which means that the call to `moveEmplace` cannot actually 
be `@trusted` unless the value is mutable.

So, at the very least, this has to be `@system`. Whether it's 
legitimate even then is a deeper question--if you mutate 
`immutable` data in the woods and nobody hears it, does it cause 
undefined behavior?


More information about the Digitalmars-d mailing list