If Proc Macros Can't Expand to Statements or Expressions, What Can They Expand To?

I'm confused at what a function-like proc macro can expand to. This gives me an error saying that it can't expand to a statement. When I take out the semicolon after cfg_aliases() it complains that it can't expand to an expression either. How then can I use a function-lie proc macro?

lib.rs ( for macro ):

extern crate proc_macro;

use proc_macro::TokenStream;

#[proc_macro]
pub fn cfg_aliases(input: TokenStream) -> TokenStream {
    r#"
    println!("Hello world");
    "#.parse().unwrap()
}

main.rs:

use cfg_aliases::cfg_aliases;

fn main() {
    cfg_aliases!()
}

I was trying to write this macro as a macro_rules! macro, but it got too complicated so I wanted to switch to a proc macro. I really just need to read the input and run some printlines.

Oh, I found it, it only works in item position, which means outside of function calls. Interesting. Looks like I might be using proc_macro_hack then.

Items can be inside function calls, BTW. They are just scoped to the function they are defined in.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.