Does the macro invocation within stringify! not work?

macro_rules! add_one {
    ($e:expr) => {
        $e + 1
    };
}
macro_rules! test_macro {
    ($e:expr) => {
        stringify!(add_one!($e))
    };
}
fn main(){
   let f = test_macro!(2);  // output: add_one!(2)
}

The output is add_one!(2), which is not the expected result(e.g. 2 + 1). It seems that the invocation of the macro in stringify!(...) does not work. So, I wonder, are all tokens in stringify treated as common text even though they match the macro invocation?

Seems that stringify just converts TokenStream on input into a TokenStream that contains &'static str and doesn’t expand input’s contents. You may try to write a procedural macro and expand the TokenStream yourself using expand_expr method, but I cannot guarantee it will work (it won’t).

1 Like

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.