Macro that accepts an expression referencing variables defined by the macro

72 views Asked by At

Is it possible to write a macro:

my_macro!(left + right)

that gets transformed into:

{
    let left = 0;
    let right = 1;
    $expr
}

where the variables are defined inside the macro? The user of the macro knows that left and right are special variable names.

1

There are 1 answers

0
cafce25 On

A declarative macro can't because of hygiene, but a very basic procedual macro can:

use proc_macro2::TokenStream;
#[proc_macro]
pub fn foo(i: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let i: TokenStream = i.into();
    quote::quote! {
        {
            let x = 1;
            #i
        }
    }
    .into()
}

when called with:

println!("{}", foo!(x + 1));

will print "2".