rust - 有没有办法在编译时获取附加程序宏的文件和模块路径?

标签 rust rust-proc-macros

我正在寻找 file!() 的等价物& module_path!()在程序宏观环境中。

例如,以下内容不起作用:
file.rs :

#[some_attribute]
const A: bool = true;
macro.rs :

#[proc_macro_attribute]
pub fn some_attribute(attr: TokenStream, input: TokenStream) -> TokenStream {
    println!("{}", file!());

    input
}

这将打印 macro.rs这是有道理的,但我想要的是file.rs .有没有办法做到这一点? module_path!() 也有类似的方法吗? ?

这样做的一个要求是必须在编译时发生。

我正在尝试在 OUT_DIR 中创建一个文件包含常量值,其中属性与模块和它们所在的文件一起添加。

最佳答案

我遇到了同样的问题,发现 Rust 为 Rust 宏(#54725)添加了一个新的实验性 API,它允许你想要什么:

#![feature(proc_macro_span)]

#[proc_macro]
pub(crate) fn do_something(item: TokenStream) -> TokenStream {
    let span = Span::call_site();
    let source = span.source_file();
    format!("println!(r#\"Path: {}\"#)", source.path().to_str().unwrap())
        .parse()
        .unwrap()
}
use my_macro_crate::*;

fn main() {
    println!("Hello, world!");
    do_something!();
}
将输出:
Hello, world!
Path: src\main.rs
重要的
除了这个 API 是实验性的之外,该路径可能不是真正的操作系统路径。如果 Span由宏生成。访问文档 here .

关于rust - 有没有办法在编译时获取附加程序宏的文件和模块路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60738538/

相关文章:

rust - 如何在数据结构中存储带有 BufReader 和 BufWriter 的 TcpStream

arrays - "cannot infer type for ` _ `"在 Rust 中对 iter 使用 map 时

debugging - 如何查看导致编译错误的扩展宏代码?

rust - 是否可以在 Rust 的过程宏中存储​​状态?

rust - 我们可以在过程宏属性中获取调用者的源代码位置吗?

rust - 为什么 Rust 找不到使用 proc_macro_attribute 生成的枚举的方法?

rust - 为什么 `&str` 实现函数(例如 `String` )的 `String::trim` 结果不像静态字符串文字?

rust - 什么是 Rust 中的后缀注释?

unit-testing - 当 PartialEq 的实现不合适时,如何断言两个变量相等?

rust - 错误: `cannot find attribute in this scope` when using custom proc_macro with attributes written with darling in rust