third draft: add bitfields to D

Timon Gehr timon.gehr at gmx.ch
Fri May 24 11:51:25 UTC 2024


On 5/6/24 01:08, Walter Bright wrote:
> https://github.com/WalterBright/documents/blob/2ec9c5966dccc423a2c4c736a6783d77c255403a/bitfields.md
> 
> Adds introspection capabilities.
> 
> https://github.com/dlang/dmd/pull/16444

Thanks, this is an improvement (though I think there would be ways to 
not require complex special cases in introspective code that does not 
deeply care about bitfields).


It seems these sentences are stale and should be deleted:

> There isn't a specific trait for "is this a bitfield". However, a bitfield can be detected by taking the address of it being a compile time error.

> A bitfield can be detected by not being able to take the address of it.


This is still wrong and should be fixed:

> The value returned by .sizeof is the same as typeof(bitfield).sizeof.

(Bitfields may have a smaller memory footprint than their type. You can 
just move it to the `.offsetof` and `.alignof` section and use the same 
wording.)


I am not sure about this:
> shared, const, immutable, __gshared, static, extern
> Are not allowed for bitfields.

Some elaboration is needed. For example: A `const` object can contain 
`const` bitfields even if the bitfields themselves were not declared 
`const`. What happens in this case?


Regarding the "Controversy" section:

The problem is not that there are no alternatives to bitfields (clearly 
there are), it is that they have the nicest syntax and semantic analysis 
support and yet they have pitfalls. It would be good to give more 
cumbersome syntax to those cases where pitfalls are in fact present.


> If one sticks with one field type (such as int), then the layout is predictable in practice, although not in specification

I mostly care about practice. (E.g, D's specified floating-point 
semantics are completely insane, but LDC is mostly sane and portable by 
default, so I have not been forced to change languages.)

> A bit of testing will show what a particular layout is, after which it will be reliable

No, absolutely not, which is the problem. If the behavior is not 
reliable, then testing on any one platform will be insufficient.

Portability/deployability is a big selling point of D, and we should be 
wary of limiting that for no good reason.

> Note that the author would use a lot more bitfields if they were in the language.

Which is why there should be basic protections in place against pitfalls.


More information about the dip.development mailing list