Sometimes you need to parse content that is not a valid Rust expression (e.g., a where clause in a trait bound). In these cases, darling will call from_invalid_expr.
To support truly arbitrary inputs like #[example(bound = where T: Deserialize<'de>, D: 'static)], you should implement both from_expr and from_invalid_expr. from_expr handles valid Rust expressions, while from_invalid_expr handles the tokens that failed expression parsing.
Recommended Pattern for syn::parse::Parse types:
If your type implements syn::parse::Parse, you can use syn::parse2 to handle both valid and invalid expressions by converting the tokens into a TokenStream.
fn from_expr(expr: &syn::Expr) -> darling::Result<Self> {
match *expr {
// Invisible delimiter when the input to the macro is passed
// by a `macro_rules!`, but we can safely ignore it
Expr::Group(ref group) => Self::from_expr(&group.expr),
_ => Ok(syn::parse2(expr.into_token_stream().clone())?)
}
.map_err(|e| e.with_span(expr))
}
fn from_invalid_expr(value: &MetaNameValueInvalidExpr) -> darling::Result<Self> {
syn::parse2(value.value.clone()).map_err(Into::into)
}