Help needed: immutable struct is a type modifier, and that's wrong and broken

RazvanN razvan.nitu1305 at gmail.com
Thu Apr 16 03:55:13 UTC 2020


On Friday, 13 March 2020 at 09:33:18 UTC, FeepingCreature wrote:
> See this bug: https://issues.dlang.org/show_bug.cgi?id=20670
>
> immutable struct S { }
>
> static if(is(S == immutable T, T)) {
>     static assert(is(S == T));
> }
>
> So what happens here is that the spec states that immutable 
> struct S is "the same as if every member had been marked 
> immutable." But that's not at all what the compiler actually 
> does: apparently, it just stores S with an immutable modifier.
>
> As the code shows, immutable modifiers can be stripped away. 
> This is of course bad, because it means that there's a type 
> "S", but there's also a type "mutable S" that can only be 
> created by template specialization or Unqual, and it can't be 
> assigned to S despite nominally being the exact same type.
>
> Help?
>
> (For now, I'll probably homebrew an Unqual that uses mixin to 
> figure out when a type has a "fake immutable modifier". But I 
> won't like it.)

There is a difference between defining a struct as immutable 
(e.g. immutable struct A {}) and declaring an immutable instance 
of a struct (e.g. immutable S a;). In the first case the 
immutable acts as a storage class specifier whereas in the second 
one it is a type constructor. Unqual is used to ditch only type 
constructors not storage class specifiers. In the case of storage 
class specifiers there is no way to get rid of them because, as 
you mentioned, there is no associated type. So from this 
perspective, I think that [1] should be fixed.

Additionally, I think that

static if(is(S == immutable T, T))

should also not pass.

The correct form should be

static if(is(S == immutable))

This way you express the fact that S is an immutably defined type 
(with a storage specifier), whereas in the first case you test if 
S is an immutably declared type (with a type constructor).

[1]https://issues.dlang.org/show_bug.cgi?id=20670


More information about the Digitalmars-d mailing list