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

FeepingCreature feepingcreature at gmail.com
Tue Sep 28 06:09:19 UTC 2021


On Monday, 27 September 2021 at 20:55:56 UTC, Paul Backus wrote:
> 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?

Yes, in a real implementation of Turducken (not just a concept 
demo), `value` would be `private` and not ref readable. It's 
purely the `ref T value` that ruins the const system, but that's 
not a necessary or even desired part of my feature set. This is 
why I'm also not interested in the current "Rebindable for 
structs" PR, because `Rebindable` exposes its value by ref and is 
thus inherently unsafe for exactly the reason you describe.

Hence the thing I asked for was "the value to be returned from a 
(non-ref) function", an operation which copies exactly the parts 
of the value that head-mutable makes mutable. ("head" == 
"by-value", pretty much exactly.)



More information about the Digitalmars-d mailing list