pub fn expr_error_wrap(
expr: &mut Expr,
error_info: &mut impl CompileErrorProvider,
)Available on crate feature
_helpers only.Expand description
Helper utilities for building procedural macros Wraps an expression in a block that includes compile-time error messages.
This function is useful when you want to show that expression is problematic
It transforms a single expression into a block containing compile_error!
calls followed by the original expression.
§Arguments
expr- The expression to wrap (will be modified in place)error_info- A struct or collection implementingCompileErrorProvider
§Behavior
If there are no errors in error_info, the expression is left unchanged.
If there are errors, the expression is wrapped in a block containing:
compile_error!statements for each error message- The original expression as the final statement
§Examples
§Basic Usage
ⓘ
let mut expr = parse_quote!(42);
let mut errors = vec![
"This is a warning".to_string(),
"Another issue found".to_string(),
];
expr_error_wrap(&mut expr, &mut errors);
assert_eq!(
quote! { #expr }.to_string(),
quote! {
{
compile_error!("This is a warning");
compile_error!("Another issue found");
42
}
}
.to_string()
);§Using Custom CompileErrorProvider Implementation
ⓘ
#[derive(Default)]
struct MacroValidator {
errors: Vec<String>,
context: String,
}
impl MacroValidator {
fn new(context: &str) -> Self {
Self {
errors: Vec::new(),
context: context.to_string(),
}
}
fn validate_field(&mut self, field_name: &str, is_valid: bool) {
if !is_valid {
self.errors.push(format!(
"Invalid field '{}' in {}",
field_name, self.context
));
}
}
}
impl CompileErrorProvider for MacroValidator {
fn no_errors(&self) -> bool {
self.errors.no_errors()
}
fn error_data(&mut self) -> Vec<String> {
self.errors.error_data()
}
}
let mut validator = MacroValidator::new("MyStruct");
validator.validate_field("name", false);
validator.validate_field("id", false);
let mut result_expr = parse_quote!(MyStruct::default());
expr_error_wrap(&mut result_expr, &mut validator);
assert_eq!(
quote! { #result_expr }.to_string(),
quote! {
{
compile_error!("Invalid field 'name' in MyStruct");
compile_error!("Invalid field 'id' in MyStruct");
MyStruct::default()
}
}
.to_string()
);§Use Cases
- Warning about deprecated or problematic usage patterns
- Validating macro input and reporting multiple issues at once
- Creating compile-time assertions with custom messages