Pre-RFC: More places for procedual macros

Currently procedual macros (like attribute macros) are only allowed to be placed on items.

However, from the book itself (not that the book is the source of all truth) it says that macros “allow creating syntax extensions”. And I think that this should also mean for things that aren’t just items since that might be a bit too broad.

So I propose that procedural macros should be able to be put onto within function blocks. This would allow for seemingly new syntax.

Example:

fn foobar() {
    #[some_macro]
    if check {
        ...
    } else {
        ...
    }
}

Problems:

  • What exactly should be passed to the macro function?
  • Could make it hard to see what the macro is modifying.
  • When should there be run? Before or after any macros on the surrounding item (I would say before as the least surprising).

Solution to 1: Could be just be the immediately following block only which would also help with the problem of understanding scope of the macros.

Alternatives:

  1. Do nothing, such “syntax extensions” should only be done with macro_rules.
  2. Extend macro_rules (maybe with a new form) to expand how it might be used because of the following reasons:

  1. All three types of brackets work for all macros which is weird.
  2. No way to have some items / blocks / exprs before the block

This is intended to be supported in the long term. The problem has to do with hygiene. The proc macro APIs we have finished today are unhygienic, and in expression contexts macro hygiene becomes very important. We didn’t want to stabilize macros on things other than items until we have stable hygienic proc macro APIs.

5 Likes

Ah cool thanks for the information.

I don’t know whether or not it makes sense to implement OpenMP or some subset of it using proc macros, but there’s a lot of things it does that are expressed as annotations on control-flow constructs, so I think it would be a good thing to look at for stuff that should be possible, when trying to generalize proc macros beyond items.

I agree, I think that when the time comes to extend proc macros the ability to work on what normally would be invalid syntax is a must.