To achieve the desired macro invocation style (process_files_in_dir!("./mydir", myLocalFunc)) and generate a wrapper function for each file in the directory, we'll need to:
Parse the function identifier instead of defining the function inline.
Dynamically generate wrapper functions based on the files found in the directory.
Since procedural macros run at compile time and cannot interact with the file system directly, we'll simulate the behavior by generating wrappers for a fixed set of files (for demonstration purposes). For a real-world scenario, you'd need a build script or runtime solution to list files.
Here's the implementation:
Updated Macro Implementation
rust
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, LitStr, Ident, Token};
struct MacroArgs {
dir_path: LitStr, // Directory path (e.g., "./mydir")
comma: Token![,], // Comma separator
func_name: Ident, // Function name (e.g., myLocalFunc)
}
impl syn::parse::Parse for MacroArgs {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
Ok(Self {
dir_path: input.parse()?,
comma: input.parse()?,
func_name: input.parse()?,
})
}
}
#[proc_macro]
pub fn process_files_in_dir(input: TokenStream) -> TokenStream {
let args = parse_macro_input!(input as MacroArgs);
let dir_path = args.dir_path.value();
let func_name = &args.func_name;
// Simulate files in the directory (replace with actual file listing logic)
let files = vec!["file1.txt", "file2.txt", "subfolder/file3.txt"];
// Generate a wrapper function for each file
let wrappers: Vec<_> = files.iter().map(|file| {
let wrapper_name = Ident::new(&format!("process_{}", file.replace(|c: char| !c.is_alphanumeric(), "_")), file.span());
quote! {
pub fn #wrapper_name() {
println!("Processing file: {}", #file);
#func_name(#file);
}
}
}).collect();
let expanded = quote! {
#(#wrappers)*
};
TokenStream::from(expanded)
}
The macro is called with a directory path and a function name: process_files_in_dir!("./mydir", my_local_func).
Parsing:
The macro parses the directory path (LitStr) and the function name (Ident).
Simulated File Listing:
For demonstration, we hardcode a list of files (file1.txt, file2.txt, etc.). In a real application, you'd use a build script or runtime logic to list files.
Wrapper Generation:
For each file, the macro generates a wrapper function:
The wrapper name is derived from the file path (e.g., process_file1_txt).
Each wrapper prints the file being processed and calls the provided function (my_local_func) with the file path.
Output:
The macro expands to multiple wrapper functions, each corresponding to a file in the directory.
Real-World File Listing
For actual file system interaction, combine this macro with a build script:
Build Script (build.rs):
rust
use std::env;
use std::fs;
use std::path::Path;
use std::process::Command;
fn main() {
let dir_path = "./mydir";
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("file_list.rs");
let files: Vec<String> = fs::read_dir(dir_path)
.unwrap()
.filter_map(|entry| {
let entry = entry.ok()?;
let path = entry.path();
if path.is_file() {
Some(path.to_str().unwrap().to_string())
} else {
None
}
})
.collect();
let content = format!("pub const FILES: &[&str] = &{:?};", files);
fs::write(dest_path, content).unwrap();
}
Modified Macro:
Include the generated file_list.rs and use FILES to generate wrappers.
rust
#[proc_macro]
pub fn process_files_in_dir(input: TokenStream) -> TokenStream {
let args = parse_macro_input!(input as MacroArgs);
let func_name = &args.func_name;
// Include the file list generated by the build script
let file_list = include!("../OUT_DIR/file_list.rs");
let wrappers: Vec<_> = file_list.FILES.iter().map(|file| {
let wrapper_name = Ident::new(&format!("process_{}", file.replace(|c: char| !c.is_alphanumeric(), "_")), file.span());
quote! {
pub fn #wrapper_name() {
#func_name(#file);
}
}
}).collect();
let expanded = quote! {
#(#wrappers)*
};
TokenStream::from(expanded)
}
Key Notes
Build Script: Required for actual file system interaction at compile time.
Wrapper Names: Sanitize file paths to create valid Rust identifiers (e.g., replace / with _).
Flexibility: Extend the macro to handle subdirectories, different file types, or additional metadata.
This approach ensures the macro generates wrappers based on the directory contents while maintaining the desired invocation style.