Here's a Rust procedural macro that processes each file in a directory using a specified function. The macro generates a wrapper function that handles directory iteration and calls your function for each file:
rust
// lib.rs in proc-macro crate
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, LitStr, Ident, Token};
use syn::parse::{Parse, ParseStream, Result};
struct MacroInput {
dir_path: LitStr,
_comma: Token![,],
func: Ident,
}
impl Parse for MacroInput {
fn parse(input: ParseStream) -> Result<Self> {
Ok(Self {
dir_path: input.parse()?,
_comma: input.parse()?,
func: input.parse()?,
})
}
}
#[proc_macro]
pub fn process_files_in_dir(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as MacroInput);
let dir_path = input.dir_path;
let func_ident = input.func;
// Generate the wrapper function
let expanded = quote! {
{
/// Wrapper function that processes all files in the directory
fn __process_dir_files() -> std::io::Result<()> {
use std::path::Path;
use std::fs;
let dir = Path::new(#dir_path);
// Handle directory reading errors
let entries = fs::read_dir(dir)?;
for entry in entries {
let entry = entry?;
let path = entry.path();
// Process only regular files
if path.is_file() {
// Call user-provided function with file path
#func_ident(&path);
}
}
Ok(())
}
// Return the wrapper function
__process_dir_files
}
};
TokenStream::from(expanded)
}
Usage Example:
rust
// In your main application
use std::path::Path;
use your_crate::process_files_in_dir;
fn main() {
// Define your file processing function
fn process_file(path: &Path) {
println!("Processing: {:?}", path.file_name().unwrap());
// Add your file processing logic here
}
// Use the macro to create a directory processor
let processor = process_files_in_dir!("./src", process_file);
// Execute the processor
match processor() {
Ok(_) => println!("All files processed successfully"),
Err(e) => eprintln!("Error processing directory: {}", e),
}
}
Key Features:
Directory Processing:
Reads the specified directory at runtime
Processes only regular files (skips directories)
Handles I/O errors properly
Wrapper Function:
Generates a function named __process_dir_files
Returns std::io::Result<()> for error handling
Captures the directory path and function identifier
Error Handling:
Propagates errors using ? operator
Returns io::Result for comprehensive error reporting
Handles both directory access and individual file errors
Usage:
First argument: directory path string literal
Second argument: function name identifier
Returns a callable function that processes the directory
Customization Options:
Recursive Processing:
rust
// Add this to the macro expansion for recursion
use walkdir::WalkDir;
// Replace the read_dir loop with:
for entry in WalkDir::new(dir) {
let entry = entry?;
if entry.file_type().is_file() {
#func_ident(entry.path());
}
}
// Add rayon for parallel iteration
use rayon::prelude::*;
// Replace the loop with:
entries.par_bridge().for_each(|entry| {
if let Ok(entry) = entry {
let path = entry.path();
if path.is_file() {
#func_ident(path);
}
}
});
Requirements:
Add to your proc-macro crate's Cargo.toml:
toml
[lib]
proc-macro = true
[dependencies]
syn = { version = "2.0", features = ["full", "extra-traits"] }
quote = "1.0"
proc-macro2 = "1.0"
The macro expands to a block that defines and returns the wrapper function
The wrapper function will:
Read the specified directory
Iterate through all entries
Call your function for each file
Return Ok(()) on success or propagate errors
The generated function is scoped to prevent name collisions
Error Cases Handled:
Invalid directory path
Permission errors
Non-existent directory
IO errors during iteration
Filesystem errors during metadata checks
This implementation provides a clean, type-safe interface for processing directory contents while maintaining proper error handling and separation of concerns.