Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 581
anderspitman Avatar asked Aug 05 '15 17:08

anderspitman


1 Answers

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
        }
    }
}
like image 135
oli_obk Avatar answered Nov 15 '22 07:11

oli_obk