DIP: add Bit Fields

Dukc ajieskola at gmail.com
Thu Mar 7 14:50:23 UTC 2024


On Thursday, 7 March 2024 at 04:26:56 UTC, Walter Bright wrote:
> https://github.com/WalterBright/documents/blob/master/bitfields.md

> The usual way to do bitfields is (culled from the DMD compiler 
> source):
> ```D
> struct S
> {
>     enum Flags : uint
>     {
>         isnothrow       = 0x0001, // nothrow
>         isnogc          = 0x0002, // is @nogc
>         isproperty      = 0x0004, // can be called without 
> parentheses
>         isref           = 0x0008, // returns a reference
>         isreturn        = 0x0010, // 'this' is returned by ref
>         isscope         = 0x0020, // 'this' is scope
>         isreturninferred= 0x0040, // 'this' is return from 
> inference
>         isscopeinferred = 0x0080, // 'this' is scope from 
> inference
>         islive          = 0x0100, // is @live
>         incomplete      = 0x0200, // return type or default 
> arguments removed
>         inoutParam      = 0x0400, // inout on the parameters
>         inoutQual       = 0x0800, // inout on the qualifier
>     }
> 
>     Flags flags;
> }
> ```

Granted that this way is pretty common, but it's far from 
optimal. `std.bitmanip.bitfields` does this a lot better, even 
more so when you have multiple-bit fields. Yes, as the DIP says 
it lacks C compatibility guarantees, but so does this solution. 
This example is thus a bit of a straw man. Please just supply an 
example with a standard library bitfield.

In the general use case, portability trumps C compatibility. 
Therefore, we should and will use `std.bitmanip` bitfields when 
we don't explicitly have to be C compatible. What the DIP is 
suggesting should be considered a special bitfield type, not the 
"normal" case.

I do not think any syntactic additions to the language itself are 
a good idea. We don't have any special syntax for normal 
bitfields either so it would be strange for C-compatible 
bitfields to have that. It'd be better that C bitfields would be 
declared with a mixin somewhere in DRuntime, its usage syntax 
preferably as close as possible to `std.bitmanip.bitfields`. The 
compiler can still recognise the call of the mixin as special, 
but from user POV it should be no different from any other mixin.


More information about the dip.development mailing list