Here's a Rust proc macro that takes a string and a function:
// In Cargo.toml
[dependencies]
proc-macro2 = "1.0"
quote = "1.0"
syn = { version = "2.0", features = ["full"] }
[lib]
proc-macro = true
// lib.rs
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, LitStr, ItemFn};
#[proc_macro]
pub fn with_string_and_function(input: TokenStream) -> TokenStream {
let input = proc_macro2::TokenStream::from(input);
let mut iter = input.into_iter();
// Parse the string literal
let string_token = iter.next().expect("Expected string literal");
let string_lit: LitStr = syn::parse2(quote! { #string_token })
.expect("First argument must be a string literal");
// Skip comma
let comma = iter.next();
if !matches!(comma, Some(proc_macro2::TokenTree::Punct(p)) if p.as_char() == ',') {
panic!("Expected comma after string literal");
}
// Parse the function
let remaining: proc_macro2::TokenStream = iter.collect();
let function: ItemFn = syn::parse2(remaining)
.expect("Second argument must be a function");
let string_value = string_lit.value();
let fn_name = &function.sig.ident;
let fn_block = &function.block;
let fn_inputs = &function.sig.inputs;
let fn_output = &function.sig.output;
// Generate code that uses both the string and function
let expanded = quote! {
{
const MESSAGE: &str = #string_value;
fn #fn_name(#fn_inputs) #fn_output #fn_block
println!("String: {}", MESSAGE);
#fn_name
}
};
TokenStream::from(expanded)
}
Usage example:
use your_crate::with_string_and_function;
fn main() {
let my_func = with_string_and_function!(
"Hello, world!",
fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
);
println!("{}", my_func("Alice"));
}
This macro:
- Takes a string literal as the first argument
- Takes a function definition as the second argument
- Creates a constant with the string value
- Preserves the function definition
- Returns the function so it can be used
You could modify this to do different things with the string and function, like:
- Use the string as a prefix for the function name
- Inject the string into the function body
- Create multiple variations of the function
- Generate documentation from the string
What specific behavior did you want the macro to have with the string and function?