Re: [PATCH 3/6] rust: add `bitfield!` macro

From: Alexandre Courbot

Date: Thu Jan 29 2026 - 08:41:21 EST


On Thu Jan 29, 2026 at 3:05 AM JST, Yury Norov wrote:
> On Wed, Jan 28, 2026 at 11:12:27PM +0900, Alexandre Courbot wrote:
>> On Wed Jan 28, 2026 at 2:27 PM JST, Yury Norov wrote:
>
> <snip>
>
>> >> > Then let's implement it better. Can you comment why the suggested API
>> >> > doesn't work for you?
>> >> >
>> >> > color.set(blue, 10);
>> >> > color.get(blue);
>> >> >
>> >> > I think it should solve the problem with name clashing.
>> >>
>> >> That syntax cannot be implemented as it is written. What type is `blue` here?
>> >
>> > 'blue' has no type because it is not a variable but keyword. We do
>> > such things in C all the time:
>> >
>> > DEFINE_FREE(kfree, void *, if (_T) kfree(_T))
>> > ^^^^^
>> > keyword that becomes a part of cleanup function name
>> >
>> > And in another email I seemingly do similar thing for python_init!()
>> > macro in rust to pick the right constructor.
>>
>> Yup, and we could do the same in Rust with a macro, but your example
>> above was not macro code (macros are always ending with a `!`).
>
> color.set!(blue, 10) is equally good, if it helps.

But not doable unfortunately, since macros cannot be declared as
methods. The closest we could get is

bitfield_set!(color, blue, 10);

>
> If someone will point to the excessive use of macros, you're safe to
> ignore it. This is the very basic fundamental type, and I believe that
> it brings enough attention and expertise to make it safe.

I think the consensus is that macros are fine if they can hide
boilerplace. For instance, the `vec!` macro declares and initializes a
vector with content and spares you the need to write a loop. A proper
and elegant bitfield initializer would fit within that category imho.

>
>> >> The closest we could get would be a macro, that would look like
>> >>
>> >> bitfield_set!(color, blue, 10);
>
> Or maybe bitfield_set!(color.blue, 10), but the above looks more natural.
> Is it possible to make it color.blue = 10 by any chance?

the `= 10` part is no problem. However I am not sure we can parse
`color.blue` safely since the macro should also support
`object.bitfield.color` as an argument and won't be able to
differenciate between the path to the bitfield and the field itself
(hopefully that makes sense).

>
> Again (and again) - usability and readability is a king, and I'm glad
> we're moving toward the right direction.

I am confident we can find something that is both nice to use and
efficient under the hood when we start extracting the bitfield macro out
of `register!` during the next cycle. We've already made good progress.