Macro to add same set of fields to each macro

Hi, I find common fields amongst a set of structs and want to automate their creation (think "is-a" relationship in OO).

For example:

struct Common { a: u8 b: u8, c: u8 }
struct SomethingA { a: u8 b: u8, c: u8, d: usize }
struct SomethingB { a: u8 b: u8, c: u8 }
etc.

The structure of Common is semantically important, so I could validly just have (good old composition over inheritance):

struct SomethingA { d: usize, common: Common }
struct SomethingA { common: Common }

but I don't like the ergonomics. I really want something like the following:

struct Common { a: u8 b: u8, c: u8}
#[inherit("Common")]
struct SomethingA { d: usize} // becomes Something A { a,b,c,d }
#[inherit("Common")]
struct SomethingB { } // becomes Something A { a,b,c }
etc.

(Unlike inheritence, SomethingA and SomethingB don't need to actually be Common so there's no need to implement any "IAmCommon" trait for example).

I've googled a bunch which hasn't yielded much...the closest seems to be defining all variations in a single macro, or something like boilermates - Rust, but neither quites fit.

My question - is there any prior art for this?

I've played around with procedural macros, and "grok" ASTs etc....but I quickly got into the wild-west where it started looking like weird and whacky abstract art .... fun times! :slight_smile:

Thanks!

You can't do this. Macros can access the literal tokens passed to them when invoked, and nothing else. There is no way to look up Common or see what fields it has. This applies to all macros, procedural and otherwise.

The only thing I can think of would be to define a macro that rewrites a struct definition passed to it to include those specific common fields. As in, this macro would have to have the fields hard-coded into it.

You could maybe do some juggling with having a derivation macro on Common that expands to a macro, but you'd be restricted to using macro_rules! for the rewrite. Which is possible, but a bit hairy.

2 Likes

I guess that's why there is so little prior art :-). Thanks @DanielKeep for your excellent and quick response :-).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.