Attribute Macro macro_magic_macros::import_tokens_proc

source ·
#[import_tokens_proc]
Expand description

An attribute macro that can be attached to a proc macro function definition that will cause it to receive the tokens of the external item referred to by its argument as input to your proc macro.

For example:

#[import_tokens_proc]
#[proc_macro]
pub fn my_macro(tokens: TokenStream) -> TokenStream {
    // `tokens` will contain the tokens of
    let item = parse_macro_input!(tokens as Item);
    // you can now do stuff with `item`
    // ...
}

Which you could use like this:

my_macro!(some_crate::some_item);

In this case the tokens variable will contain the tokens for the some_crate::some_item item, as long as it has been marked with #[export_tokens].

Note that this attribute can only be used within a proc macro crate.

§Overriding MACRO_MAGIC_ROOT:

You can also provide a module path as an optional argument to this attribute macro and that path will be used as the override for MACRO_MAGIC_ROOT within the context of code generated by this attribute. Instead of a Path, you are also free to provide any Expr that evaluates to something compatible with Into<String> so you can dynamically generate this path based on format! and other string manipulation machinery, if necessary.

Here is an example of providing a Path as the override for MACRO_MAGIC_ROOT:

#[import_tokens_proc(my_crate::__private::macro_magic)]
pub fn my_macro(tokens: TokenStream) -> TokenStream {
    // ..
}

and here is an example of providing an Into<String>-compatible Expr as the override for MACRO_MAGIC_ROOT:

#[import_tokens_proc(format!("{}::__private::macro_magic", generate_crate_access_2018("my_crate")))]
pub fn my_macro(tokens: TokenStream) -> TokenStream {
    // ..
}