r/rust•
Cyclip

Using attribute macros, how would I get the inner function code as TokenStream?

I'm only able to get the code including the function declaration but I just want to separate the code inside the function. My (relevant) code so far is

pub fn test_macro(_metadata: TokenStream, item: TokenStream) -> TokenStream {
    let input_fn: Item = syn::parse(item).expect("failed to parse input");
}

But input_fn as a string is just fn test() { println!("test"); }, whereas I want just println!("test");. My overall goal is just to modify the function's inner code but I have no idea how to process input_fn.

Posted Jul 30, 2021, 7:47 PM UTC

21
esitsu•

Item is an enum that includes all sorts of things that can be parsed. You can either match the enum or parse to an ItemFn directly. Then from there you can get the block which contains a list of statements which compose the function body.

7