Search code examples
rustrust-macrosrust-decl-macros

Pass entire macro input to another macro


I'm trying to make a simple macro that invokes vec! with whatever it receives then does some simple processing before returning the new vector:

macro_rules! sorted_vec {
    ($x:expr) => {
        {
            let v = vec![$x];
            v.sort();
            v
        }
    }
}

The problem is that my macro is trying to parse the syntax, so it complains about commas, etc. That makes sense, but I'm not sure how to get around it. I don't think expr is the correct fragment specifier to use. How do I get it to pass the raw input on to vec! without processing it?


Solution

  • The fragment specifier you want is tt (Token-Tree). A tt is simply an arbitrary valid rust-token like a keyword or an operator or a bracket/block/square-bracket with arbitrary tts inside. Combined with a variadic macro, you get infinite tokens that can be directly passed to another macro

    macro_rules! sorted_vec {
        ($($x:tt)*) => {
            {
                let mut v = vec![$($x)*];
                v.sort();
                v
            }
        }
    }