我需要将文本文件或文本文件的内容传递给过程宏,以便过程宏在编译时根据该文本文件的内容进行操作。也就是说,文本文件配置宏的输出。其用例是定义宏构建到库中的寄存器映射的文件。
第二个要求是文本文件由 正确处理Cargo
,以便对文本文件的更改触发重新编译,就像对源文件的更改触发重新编译一样。
我最初的想法是使用宏创建一个static
字符串include_str!
。这解决了第二个要求,但我不知道如何将其传递给宏 - 此时我只有要传入的字符串的标识符:
use my_macro_lib::my_macro;
static MYSTRING: &'static str = include_str!("myfile");
my_macro!(MYSTRING); // Not the string itself!
Run Code Online (Sandbox Code Playgroud)
我可以将一个字符串传递给宏,其中包含字符串文字中的文件名,然后在宏内打开该文件:
my_macro!("myfile");
Run Code Online (Sandbox Code Playgroud)
此时我有两个问题:
Span
,但似乎一般不会(也许我错过了一些东西?)。Cargo
如何使文件 make触发更改后的重新编译并不明显。我必须强制执行的一个想法是在宏的输出中添加 an include_str!("myfile")
,这有望导致编译器意识到“myfile”,但这有点麻烦。有什么方法可以做我想做的事情吗?也许通过某种方式获取外部创建的宏内的字符串内容,或者可靠地获取调用 rust 文件的路径(然后Cargo
正确进行处理更改)。
顺便说一句,我读过很多地方告诉我无法访问宏内变量的内容,但在我看来,这正是宏quote
正在做的事情#variables
。这是如何运作的?
所以事实证明,这基本上是可能的,就像我希望使用稳定的编译器一样。
如果我们接受需要相对于板条箱根进行工作,我们就可以这样定义我们的路径。
有用的是,在宏代码内,std::env::current_dir()
将返回当前工作目录作为包含调用站点的包的根。这意味着,即使宏调用位于某个 crate 层次结构内,它仍然会返回在宏调用位置有意义的路径。
下面的示例宏基本上满足了我的需要。为了简洁起见,它的设计目的不是正确处理错误:
extern crate proc_macro;
use quote::quote;
use proc_macro::TokenStream;
use syn::parse::{Parse, ParseStream, Result};
use syn;
use std;
use std::fs::File;
use std::io::Read;
#[derive(Debug)]
struct FileName {
filename: String,
}
impl Parse for FileName {
fn parse(input: ParseStream) -> Result<Self> {
let lit_file: syn::LitStr = input.parse()?;
Ok(Self { filename: lit_file.value() })
}
}
#[proc_macro]
pub fn my_macro(input: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(input as FileName);
let cwd = std::env::current_dir().unwrap();
let file_path = cwd.join(&input.filename);
let file_path_str = format!("{}", file_path.display());
println!("path: {}", file_path.display());
let mut file = File::open(file_path).unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
println!("contents: {:?}", contents);
let result = quote!(
const FILE_STR: &'static str = include_str!(#file_path_str);
pub fn foo() -> bool {
println!("Hello");
true
}
);
TokenStream::from(result)
}
Run Code Online (Sandbox Code Playgroud)
可以通过以下方式调用
my_macro!("mydir/myfile");
Run Code Online (Sandbox Code Playgroud)
其中mydir
是调用包根目录中的目录。
这使用了在宏输出中使用 an 的技巧include_str!()
来导致对myfile
. 这是必要的并且符合预期。如果从未实际使用过,我希望它能够被优化。
我很想知道这种方法在任何情况下是否都会失败。
与我原来的问题相关,当前每晚source_file()
在Span
. 这可能是实现上述内容的更好方法,但我宁愿坚持使用稳定版。此问题的跟踪问题在这里。
编辑:当包位于工作区中时,上述实现会失败,此时当前工作目录是工作区根目录,而不是板条箱根目录。这很容易解决,如下所示(插入在cwd
和file_path
声明之间)。
let mut cwd = std::env::current_dir().unwrap();
let cargo_path = cwd.join("Cargo.toml");
let mut cargo_file = File::open(cargo_path).unwrap();
let mut cargo_contents = String::new();
cargo_file.read_to_string(&mut cargo_contents).unwrap();
// Use a simple regex to detect the suitable tag in the toml file. Much
// simpler than using the toml crate and probably good enough according to
// the workspace RFC.
let cargo_re = regex::Regex::new(r"(?m)^\[workspace\][ \t]*$").unwrap();
let workspace_path = match cargo_re.find(&cargo_contents) {
Some(val) => std::env::var("CARGO_PKG_NAME"),
None => "".to_string()
};
let file_path = cwd.join(workspace_path).join(input.filename);
let file_path_str = format!("{}", file_path.display());
Run Code Online (Sandbox Code Playgroud)