Below is an example of a procedural macro crate that defines an attribute macro which takes a string literal argument and a function. In this example, the macro prints the supplied string before executing the original function’s code.
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, AttributeArgs, ItemFn, Lit, NestedMeta};
/// An attribute macro that takes a string literal and a function.
/// It injects a println! call with the given string at the beginning of the function.
#[proc_macro_attribute]
pub fn greet(attr: TokenStream, item: TokenStream) -> TokenStream {
// Parse the attribute arguments as a list.
let args = parse_macro_input!(attr as AttributeArgs);
// Expect exactly one argument: a string literal.
if args.len() != 1 {
return syn::Error::new_spanned(
&args[0],
"expected exactly one string literal argument",
)
.to_compile_error()
.into();
}
// Extract the string literal.
let message = match &args[0] {
NestedMeta::Lit(Lit::Str(lit_str)) => lit_str.value(),
_ => {
return syn::Error::new_spanned(
&args[0],
"expected a string literal",
)
.to_compile_error()
.into();
}
};
// Parse the function the attribute is attached to.
let input_fn = parse_macro_input!(item as ItemFn);
let fn_name = &input_fn.sig.ident;
let fn_vis = &input_fn.vis;
let fn_sig = &input_fn.sig;
let fn_block = &input_fn.block;
// Generate a new function that prints the message then executes the original code.
let expanded = quote! {
#fn_vis #fn_sig {
println!("{}", #message);
#fn_block
}
};
TokenStream::from(expanded)
}
Explanation:
We use the syn crate to parse the attribute arguments (expected to be one string literal) and the function item.
The macro then generates a new version of the function. It is identical to the original except that it first prints the provided message.
The quote crate is used to easily generate Rust code from the syntax tree.
3. Use the Macro in an Example Binary Crate
To test the macro, create a new binary crate (for example, called example) and add the following to its Cargo.toml:
Then, in your src/main.rs (or another file), write:
rust
use hello_proc_macro::greet;
#[greet("Hello, world!")]
fn my_function() {
println!("Inside the function.");
}
fn main() {
my_function();
}
When you run cargo run in the binary crate, you should see:
code
Hello, world!
Inside the function.
This example demonstrates how to create a Rust procedural macro that takes both a string literal and a function, then injects code into that function using the provided string. You can extend or modify the macro to fit your specific needs.