Sugar proposal: @_ as unused fields name generator

Foreword: after couple of years trying zig in embedded/baremetal development I have convinced myself, that it is relatively safe to switch to it completely (at least for certain types of projects).

During my adoption of zig, I tried several approaches to handle io registers for MCU/MPU and even bus connected devices and in the end packed structs have won (obviously).

The thing, which tired me a lot was rendering/rerendering names for unused fields. May be my approach seems odd, but I prefer describe only those io registers and fields of a such, those really necessary to commit changes. Describing the whole bunch of regs/fields for even simple STM’s MCU would take too long, so this seems rewarding way of development: add definitions for only regs/fields we use in current time.

So, it would be beneficial to have similar engine, which just does the same thing which it does for ignored variable _ but for unused fields, those forced to be declared to fill gaps in between used registers/fields.

Instead of writing and maintaining (renaming) unused fields of

const BareMetalReg = packed struct(u32) {
   usefulField: u5 = undefined,
   _: u3 = 0, // three ignored bitfields
   anotherUsefulField: enum(u1) {....} = undefined,
   __: u3 = 0, // two ignored fields
   mostUsefulField: u1 = undefined,
   ___: u19 = 0, // more ignored fields so far...
};

we can write:

const BareMetalReg = packed struct(u32) {
   usefulField: u5 = undefined,
   _unused: u3 = 0,
   anotherUsefulField: enum(u1) {....} = undefined,
   _unused: u3 = 0,
   mostUsefulField: u1 = undefined,
   _unused: u19 = 0,
};

And then, when we need to embed new useful field, we don’t have to rename others by any means. And GitNazis can not punish us any more on reviews for this!!!

In my implementation I decided to utilize unused @_ builtin as a placeholder symbol. It mimics unused variable in func. scope (_) and does not break its current usage in struct’s scope. Moreover, it attracts attention and denotes, that compiler will do something unusual under the hood in this place. It is also pretty fast to write (sorry, I know that zig must be easy readable, not writable :slight_smile: ). There was an option to stick to something like @”_”, but try to type it yourself and make no mistake.

Here is my draft implementation for @_, sorry, I haven’t moved my copy of zig’s src to codeberg. It works for me so far, of course, there are bugs! Anyway, give it a try!

1 Like

Related proposal: Change meaning of underscore from actual identifier name to ignoring the value being named · Issue #4164 · ziglang/zig · GitHub

Also unrelated to your main issue, avoid setting packed struct members to undefined as that doesn’t have well defined behavior. Related: Proposal: make `packed` `undefined` semantics consistent with those of integers · Issue #25279 · ziglang/zig · GitHub