dtolnay / paste

Macros for all your token pasting needs
Apache License 2.0
983 stars 53 forks source link

Access to variable declared in macro #80

Closed BratSinot closed 2 years ago

BratSinot commented 2 years ago

Greetings!

I don't know, maybe it related with #7, but I can't use variable from macro:

use paste::paste;

macro_rules! gen {
    ( $name:tt, $plural:tt ) => {
        paste! {
            let [<$name $plural _str >] = stringify!([<Str $name:camel $plural>]);
        }
    };
}

fn main() {
    gen!("foo", "s");

    println!("{}", foos_str);
}

I'm getting:

error[E0425]: cannot find value `foos_str` in this scope
  --> src/main.rs:14:20
   |
14 |     println!("{}", foos_str);
   |                    ^^^^^^^^ not found in this scope
dtolnay commented 2 years ago

This is the correct behavior.

Your macro is basically like the example macro in the explanation on this page: https://danielkeep.github.io/tlborm/book/mbe-min-hygiene.html.

BratSinot commented 2 years ago

macro is basically like the example macro in the explanation on this

Thanks.

I had my guess that it was in scope, but any way to get around this without let var = macro!();?

dtolnay commented 2 years ago

Yeah, you can make gen a proc macro and make it declare the local with a call site span.

I'll close this issue since paste wouldn't be involved at that point.