Macro body expand out optional matches not captured in meta variables

⚓ rust    📅 2025-06-19    👤 surdeus    👁️ 3      

surdeus

I think something like this was asked before but I'm having a hard time locating it.

Say, I want to match against structures which have various optional parts. In simplified form:

macro_rules! foo {
  ($(&)? $(::)? $($t:ident)::+) => { ... }
}

Now, in the macro body, I want to expand out & or :: only if it appeared in the pattern. The only way I know to handle this is. I don't know how to capture the & or :: in meta variables to capture them and my workaround is to write out all the variants:

macro_rules! foo {
  (& :: $($t:ident)::+) => { ... };
  (  :: $($t:ident)::+) => { ... };
  (&    $($t:ident)::+) => { ... };
  (     $($t:ident)::+) => { ... };
}

I know I can do this straightforwardly with proc_macros, but I wanted to see if there were any way these days to do it with declarative macros.

And in case folks try to suggest I match the whole thing against an expr or something, I actually need the various parts of the matched construct to produce different types of things (path, pattern) in the macro body.

1 post - 1 participant

Read full topic

🏷️ rust_feed