Macro rules application in attributes

I find macro_rules! easier to work with compared to proc macros and I've seen many instances of this pattern:

macro_rules! rewrite {
	...
}

rewrite! {
  struct T { }
}

However, I think the attribute syntax is preferable when it comes to processing declarations:

#[rewrite]
struct T {}

Today, this is easy to work around: either define rewrite as proc_macro_attribute and wrap the input, or define a general proc macro #[macro(rewrite)] to be used for any macro rules which works but there will be some boilerplate to manage.

The idea is to make it possible to apply macro rules directly to items:

#[rewrite!]
struct T {}

So that you can match any kind of items in the rules one by one and rewrite.

1 Like

Have you seen the RFC 3697-declarative-attribute-macros - The Rust RFC Book? The RFC 3698-declarative-derive-macros - The Rust RFC Book might also be of interest to you.

5 Likes

#![feature(macro_attr)], the unstable implementation of that RFC, is usable on nightly right now.

4 Likes

TBH, I think that's only true when it leaves the item alone, just adding new items.

If it's rewriting it to be something different, I'd rather the proc macros were also enclosing.

This does seem like a personal preference, that's why I suggested to reuse macro syntax (with an exclamation mark) to also distinguish between macros and attributes.