Rust函数名称(调用方)或宏内的任何其他上下文

时间:2019-06-22 19:06:49

标签: rust macros

Rust中是否有一种方法可以在宏中获取“调用”函数名称或任何其他上下文信息?

示例:

#[macro_export]
macro_rules! somemacro {
    ( $x:expr ) => {
        {
          // access function name (etc..) that called this macro
        }
    };
}

1 个答案:

答案 0 :(得分:1)

这可以使用程序宏来完成:

get_the_title();

Cargo.toml:

extern crate proc_macro;
use proc_macro::TokenStream;

#[proc_macro_attribute]
pub fn with_name(_: TokenStream, item: TokenStream) -> TokenStream {
    let mut input = syn::parse_macro_input!(item as syn::ItemFn);

    let fn_name = input.ident.to_string();
    let const_decl = quote::quote! {
        const THIS_FN: &str = #fn_name;
    };

    input.block.stmts.insert(0, syn::parse(const_decl.into()).unwrap());

    let output = quote::quote! {
        #input
    };

    output.into()
}

可以用作:

[package]
name = "with_name"
version = "0.1.0"
edition = "2018"

[lib]
proc-macro = true

[dependencies]
quote = "0.6.12"
syn = { version = "0.15.37", features = ["full"] }

还要注意,如果您只关心模块,there is a built-in macro for that

#[with_name::with_name]
fn foo() {
    println!("Name: {}", THIS_FN);
}

fn main() {
    foo();
}

(link to playground)