| Crates.io | module_path_extractor |
| lib.rs | module_path_extractor |
| version | 0.1.0 |
| created_at | 2025-02-24 00:30:09.136905+00 |
| updated_at | 2025-02-24 00:30:09.136905+00 |
| description | A Rust procedural macro helper for determining the module path of macro invocations. |
| homepage | https://github.com/eboody/module_path_extractor |
| repository | https://github.com/eboody/module_path_extractor |
| max_upload_size | |
| id | 1566771 |
| size | 10,444 |
This Rust utility provides a way to determine the module path of a procedural macro invocation. It is particularly useful when writing procedural macros that need to infer their context within a Rust module hierarchy.
"crate::task::workflow").mod foo {}) and external (mod foo;).pub mod, pub(crate) mod, and pub(super) mod declarations correctly./ and \ in paths).This module requires Rust nightly because it uses the proc_macro_span feature.
Add the following to Cargo.toml:
[dependencies]
proc-macro2 = "1"
In your Rust crate, enable the nightly feature:
#![feature(proc_macro_span)]
This module provides a function get_pseudo_module_path() that returns the inferred module path as a String.
mod task {
#[some_macro] // This macro should return "crate::task"
fn example() {}
}
Output:
"crate::task"
pub mod task {
pub mod workflow {
#[some_macro] // Should return "crate::task::workflow"
fn example() {}
}
}
Output:
"crate::task::workflow"
When used inside a procedural macro:
#[proc_macro]
pub fn example_macro(_input: TokenStream) -> TokenStream {
let module_path = get_pseudo_module_path();
println!("Macro invoked in module: {}", module_path);
TokenStream::new()
}
Invoking the macro inside src/workflow.rs:
workflow::example_macro!();
Output:
Macro invoked in module: "crate::workflow"
It uses proc_macro::Span to get:
mod foo {}).crate::task::workflow).mod foo {}) and external (mod foo;) modules.crate::task::workflow).proc_macro_span feature).Pull requests and issues are welcome! Feel free to improve the logic or add more test cases.
This project is licensed under the MIT License.