third draft: add bitfields to D

Quirin Schroll qs.il.paperinik at gmail.com
Mon Jul 29 13:26:29 UTC 2024


On Monday, 29 July 2024 at 07:53:09 UTC, IchorDev wrote:
> On Friday, 26 July 2024 at 00:08:12 UTC, Quirin Schroll wrote:
>> I like it. The only thing that’s odd to me is `int: 21 foo, 
>> bar`. It looks much more like `21` is in line with `foo` and 
>> `bar`, but it’s to be read as `int: 21` `foo` `bar`. We could 
>> agree to use no space, i.e. `int:21`, or use something other 
>> than `:`, e.g. `int{21}`. That looks much more like a type and 
>> `int{21} foo, bar` looks much more like a list of variables 
>> declared to be of some type. Essentially, `int[n]` is a static 
>>  array of `n` values of type `int`, whereas `int{n}` is a 
>> single `n`-bit signed value. As per `int`, `n` is 32 or lower. 
>> For `bool` only `bool{1}` would be possible
>
> Good idea about `int{21}`! The `int: 21` syntax was a bit of a 
> cop-out because I couldn’t think of anything better.
>
>> (maybe also `bool{0}`, if we allow 0-length bitfields.
>
> No harm in doing so I suppose. Even better if they’re actually 
> 0 bytes, heh.
>
>> In general, `extern(D)` bitfields should be allowed to be 
>> optimized.
>
> If you mean field reordering, then that did *not* work with 
> structs, so I’m inclined to view this idea with some healthy 
> skepticism.

I don’t; I rather meant specification-level optimization, i.e. D 
should find its own layout which would be fully specified and 
need not be compatible with C. In that regard, e.g. if you had 
`ubyte{7} a, b` (or `ubyte{7}[2]`), the language could require 
the bits to be laid out as:
```
AAAA AAAB BBBB BB00
```
or
```
AAAA AAA0 BBBB BBB0
```
(`A`: bit part of `a`; `B`: bit part of `b`; `0`: padding)

The specification could say: “A block of bit fields occupies 
exactly the sum number of bits rounded up to the next multiple of 
8. The difference in those numbers is called *padding bits.* If 
after a bit field a byte boundary is not reached and the next bit 
field would overstep the next byte boundary and enough padding 
bits are left to align the next bit field with that byte 
boundary, exactly that many padding bits are inserted here. 
Otherwise, bit fields are laid out directly next to each other. 
Remaining padding bits are inserted at the end of a bit field 
block.” This is not a suggestion, but a demonstration how a spec 
can optimize; layout would be predictable.


More information about the dip.development mailing list