Procedural Macros are really hard to understand
i'm tring to making a time\_it attribute like macro that can calculate the time of function execution like python decorators,
i think i follow the steps in the rust book but the rust book is not clear enough it only goes with Derive macro only and skip the others
here is an example of my implementation./macro_test/my_macro/sec/lib.rs
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::{parse_macro_input, AttributeArgs, Expr};
#[proc_macro_attribute]
pub fn time_it(args: TokenStream, input: TokenStream) -> TokenStream {
let args = parse_macro_input!(args as AttributeArgs);
let input = parse_macro_input!(input as Expr);
let call_site = Span::call_site();
quote! {
let start = std::time::Instant::now();
let result = #input;
let elapsed = start.elapsed();
println!("{} ms", (elapsed.as_secs() * 1000) + (elapsed.subsec_nanos() / 1_000_000) as u64);
result
}
.into()
}
./macro_test/my_macro/Cargo.toml
[package]
name = "my_macro"
version = "0.1.0"
edition = "2021"
[lib]
name = "my_macro"
path = "./src/lib.rs"
proc-macro = true
[dependencies]
proc-macro2 = "1.0.50"
quote = "1.0.23"
syn = { version = "1.0.107", features = ["full"] }
./macro_test/src/main.rs
use my_macro::time_it;
fn main() {
run();
}
#[time_it]
fn run() {
println!("Hello, world!");
}
./macro_test/Cargo.toml
[package]
name = "macro_test"
version = "0.1.0"
edition = "2021"
[dependencies]
my_macro = { path = "./my_macro" }
it gives me this error:
error: expected expression
--> src\main.rs:8:1
|
8 | fn run() {
| ^^
error[E0425]: cannot find function `run` in this scope
--> src\\main.rs:4:5
|
4 | run();
| ^^^ not found in this scope
For more information about this error, try `rustc --explain E0425`.
error: could not compile `macro_test` due to 2 previous errors
finally i want a good resource how to be more professional in macros, thanks