------ void fun() @safe { union U { immutable int x; int y; } U u; u.y = 1; assert(u.x == 1); u.y = 2; assert(u.x == 2); // look ma! I broke immutability! } ------
Basically, immutable cannot be allowed to overlap with anything mutable, otherwise there will be a way to break the immutability guarantee.
Unfortunately, fixing this may prove to be a challenge, because std.typecons.Rebindable uses a union of (possibly) immutable and mutable fields in order to achieve rebindability. Arguably, though, some kind of explicit cast ought to be required in that case. Either that, or we impose the non-overlapping restriction only in @safe code, so that @system code can continue using unions to do black magic with immutability.
https://github.com/D-Programming-Language/dmd/pull/5467
Rebooted as: https://github.com/dlang/dmd/pull/5940
Commits pushed to master at https://github.com/dlang/dmd https://github.com/dlang/dmd/commit/09ed87c973fbcb777806506f7e05fbed30a3f355 fix Issue 13537 - Unions may break immutability https://github.com/dlang/dmd/commit/72077372aec4aa77899885fc5cffbdbc5d289021 Merge pull request #5940 from WalterBright/fix13537 fix Issue 13537 - Unions may break immutability
Commits pushed to stable at https://github.com/dlang/dmd https://github.com/dlang/dmd/commit/09ed87c973fbcb777806506f7e05fbed30a3f355 fix Issue 13537 - Unions may break immutability https://github.com/dlang/dmd/commit/72077372aec4aa77899885fc5cffbdbc5d289021 Merge pull request #5940 from WalterBright/fix13537