second draft: add Bitfields to D

Timon Gehr timon.gehr at gmx.ch
Sat May 4 23:01:12 UTC 2024


On 5/4/24 22:17, Walter Bright wrote:
> On 5/4/2024 10:05 AM, Timon Gehr wrote:
>> This is explicitly called a `union`, so I really do not see what you 
>> are trying to say.
> 
> An anonymous union is simply a way to specify layout. No actual union is 
> created, as there is no point to it. How would one refer to an anonymous 
> union? The same goes for anonymous structs.
> ...

Well, now you are simply slicing the terminology in a weird way. `union` 
and `struct` are tools to lay out data, anonymous or otherwise, whether 
you generate typeinfo or otherwise.

> 
>> Clearly bitfields are a new and distinct way fields can share the same 
>> `.offsetof` in D. Before bitfields, such fields would overlap given 
>> they both were of a type with a positive size. With bitfields there is 
>> no such overlap.
> 
> Bitfields do overlap, which is why they are accessed with shift and mask.
> ...

They do not overlap if not put in a union (anonymous or otherwise). 
Otherwise, changing the value of one bitfield would affect the value of 
another one. The fact that they occupy space in the same byte and that 
the processor can only address memory at byte granularity does not imply 
that the bitfields themselves overlap.

> Besides, the context here is with existing introspection. Existing 
> introspection will treat them as overlapping fields.
> 
> 
>> BTW: what about `sizeof`? I think in C++ this is disallowed on a 
>> bitfield.
> 
> ```
> struct S { int b:3; }
> pragma(msg, S.b.sizeof);
> ```
> prints 4LU, as it applies to the type. To get the field width, use .max, 
> as already discussed.

Well, then code that is set up to work with data using `.tupleof`, 
`.offsetof` and `.sizeof` will silently break. Whether you acknowledge 
that or not, it's simply the truth.

You are breaking the previous invariant that data in a struct lives at 
relative addresses `data.offsetof..data.offsetof+data.sizeof`.


More information about the dip.development mailing list