Enumerated Unions (sum types)
Paul Backus
snarwin at gmail.com
Thu Sep 12 09:44:01 UTC 2024
On Thursday, 12 September 2024 at 03:22:07 UTC, Steven
Schveighoffer wrote:
> I'm pretty sure I know, but the active field is the one last
> set, correct?
Yes.
>> Access to the tag field of an enum union, if it exists, is
>> always @system.
>
> Does this mean `obj.__tag` is `@system`? Surely, having this
> knowledge is not a safety violation.
`__tag` is an rvalue property that returns an index. Accessing it
is `@safe`.
The tag field is a hidden field whose content is unspecified.
Accessing it is `@system`.
They are two different things.
> I think your example with the `@trusted` attribute is not safe,
> because the type in question may not be `@safe` to return (i.e.
> copy constructor not `@safe`).
It returns by reference, so no copy constructor is called.
> The proposal should address taking the address of any member,
> especially in @safe code. i.e. this is currently allowed:
>
> ```d
> @safe:
> void foo(ref int x)
> {
> x = 5;
> }
>
> union U
> {
> ubyte[4] buf;
> int x;
> }
>
> void bar()
> {
> U u = {buf: [ 1, 2, 3, 4] };
> foo(u.x);
> }
> ```
>
> Such an example would not update the `__tag` even though the
> last value set would be via `.x`.
Good catch.
> The proposal should address what happens when you switch types,
> in terms of lifetime management. Is the prior active field
> destroyed? Is the memory blitted with field.init before
> assigning? Is this a construction or an assignment? Is it
> runtime dependent?
>
> None of the examples show an enum union switching types, so
> maybe I'm misunderstanding something.
The intent is that the previous value is destroyed, but you're
right that the proposal does not address this.
More information about the dip.ideas
mailing list