darling_core/util/require_ident.rs
1use crate::Error;
2use syn::Ident;
3
4/// Attaches error message to `Option<Ident>`, turning it into `darling::Result<Ident>`,
5/// so it composes nicely with `#[darling(with = ...)]` on a `struct` deriving [`FromField`](crate::FromField)
6///
7/// Using `#[derive(FromField)]` requires the `ident` field, if present, to be `Option<Ident>`.
8/// This is correct if you will use this `struct` as both part of a tuple struct, and a struct with
9/// named fields.
10///
11/// However, if you don't need to do that, then there's no need to wrap it in an `Option`.
12///
13/// ```ignore
14/// #[derive(FromField)]
15/// struct Field {
16/// // Without #[darling(with)], this must be `ident: Option<syn::Ident>`
17/// #[darling(with = darling::util::require_ident)]
18/// ident: syn::Ident,
19/// }
20///
21/// #[derive(FromDeriveInput)]
22/// struct Input {
23/// data: darling::ast::Data<darling_core::util::Ignored, Field>,
24/// }
25///
26/// let input = Input::from_derive_input(&parse_quote! {
27/// struct Demo<T> {
28/// hello: T
29/// }
30/// })?;
31///
32/// let fields = input.data.take_struct()?;
33/// let first_field = fields.into_iter().next()?;
34///
35/// // Not wrapped in `Some`!
36/// assert_eq!(first_field.ident, Ident::new("hello", Span::call_site()));
37/// ```
38pub fn require_ident(ident: Option<Ident>) -> crate::Result<Ident> {
39 ident.ok_or_else(|| Error::custom("expected identifier"))
40}