Issue with nested macro_rules! and matching types with mutable borrow

Dear community,

I am developing a macro that receives the prototype of a function and needs to generate different code depending on its arguments. Particularly, I need to distinguish when a mutable reference is passed and when not.
I have included below a code snippet that reproduces the issue in a very simple level. I have no problem matching when the expression '&mut u32' is passed directly to the macro. Then I can identify the &mut and extract the type u32 - this is Option 1 in the snippet below.
However when I need to use nested macros (Option 2) and I need to pass the type again to another invocation of the macro, I cannot seem to find a rule that matches &mut u32.

macro_rules! generate {
    // for option 1
    (@option1 $arg_name:ident : &mut $arg_ty:ty ) => {let $arg_name : &mut $arg_ty = 2;};

    // for option 2
    (@option2 $arg_name:ident : $arg_ty:ty ) => { generate!(@evaluate $arg_name : $arg_ty) };
    (@evaluate $arg_name:ident : &mut $arg_ty:ty ) => { let $arg_name : &mut $arg_ty = 2; };   // does not match
    //(@evaluate $arg_name:ident : $arg_ty:ty ) => { let $arg_name : $arg_ty = 2; };   // matches
}

fn main() {
    generate!(@option1 a: &mut u32); // option 1: works
    generate!(@option2 a: &mut u32); // option 2: does not work
}

This keeps giving me the error "no rules expected this token in macro call", pointing to the token $arg_ty in generate!(@evaluate $arg_name : $arg_ty). But $arg_ty should simply contain &mut u32. And it seems to me that there is a rule for that - but it doesn't match.

What am I missing? Thank you in advance for the help!

This came up recently. (TL;DR: "any type" is not guaranteed to start with &mut, so it can't be matched by &mut.)

Thank you for the fast reply, yes this is exactly my issue!

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.