I am working on a Rust macro that needs to accept the file name as a argument. Based on the file name I want to parse and do some operations and generate some code. I believe proc_macro
in Rust should help me achieve my requirements. However, I am facing issues passing file!()
as argument to the procedural macro. The idea is to get the file name via the file!()
macro and pass it as argument to my procedural macro. This is my current implementation:
// lib.rs - proc_macro crate
#[proc_macro]
pub fn my_macro(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as LitStr);
// perform operation on input string
let expanded = quote! {
#output_str
};
TokenStream::from(expanded)
}
fn main() {
let dir_name = my_macro!(file!());
println!("Dir name: {:?}", dir_name);
}
With this approach, I am getting compiler error:
error: expected string literal
--> src/main.rs
|
12 | let dir_name = my_macro!(file!());
| ^^^^
If I pass in the static strings, it works, for example:
let dir_name = my_macro!("my_string");
I am not sure how to pass the file name dynamically to procedural macros. Is there any other way to achieve this? Any help/reference is appreciated.
I am working on a Rust macro that needs to accept the file name as a argument. Based on the file name I want to parse and do some operations and generate some code. I believe proc_macro
in Rust should help me achieve my requirements. However, I am facing issues passing file!()
as argument to the procedural macro. The idea is to get the file name via the file!()
macro and pass it as argument to my procedural macro. This is my current implementation:
// lib.rs - proc_macro crate
#[proc_macro]
pub fn my_macro(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as LitStr);
// perform operation on input string
let expanded = quote! {
#output_str
};
TokenStream::from(expanded)
}
fn main() {
let dir_name = my_macro!(file!());
println!("Dir name: {:?}", dir_name);
}
With this approach, I am getting compiler error:
error: expected string literal
--> src/main.rs
|
12 | let dir_name = my_macro!(file!());
| ^^^^
If I pass in the static strings, it works, for example:
let dir_name = my_macro!("my_string");
I am not sure how to pass the file name dynamically to procedural macros. Is there any other way to achieve this? Any help/reference is appreciated.
Share Improve this question asked Mar 13 at 11:11 Abhijit NathwaniAbhijit Nathwani 4341 gold badge7 silver badges18 bronze badges 1 |1 Answer
Reset to default 1You can't pass the result of a macro to another macro, because macros get evaluated outside-in.
However, if you just need to get the file in which your macro was invoked, you can just use proc_macro2::Span::source_file
, taking Span from any of your input tokens.
file!()
. – kmdreko Commented Mar 13 at 16:43