darling_core/options/
from_meta.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
use std::borrow::Cow;

use proc_macro2::TokenStream;
use quote::ToTokens;
use syn::parse_quote;

use crate::ast::Data;
use crate::codegen::FromMetaImpl;
use crate::error::Accumulator;
use crate::options::{Core, ParseAttribute, ParseData};
use crate::util::Callable;
use crate::{Error, FromMeta, Result};

pub struct FromMetaOptions {
    base: Core,
    /// Override for the default [`FromMeta::from_word`] method.
    from_word: Option<Callable>,
    /// Override for the default [`FromMeta::from_none`] method.
    from_none: Option<Callable>,
}

impl FromMetaOptions {
    pub fn new(di: &syn::DeriveInput) -> Result<Self> {
        (FromMetaOptions {
            base: Core::start(di)?,
            from_word: None,
            from_none: None,
        })
        .parse_attributes(&di.attrs)?
        .parse_body(&di.data)
    }

    /// Get the `from_word` method body, if one exists. This can come from direct use of
    /// `#[darling(from_word = ...)]` on the container or from use of `#[darling(word)]` on
    /// a unit variant.
    #[allow(
        clippy::wrong_self_convention,
        // The reason is commented out due to MSRV issues.
        // reason = "This matches the name of the input option and output method"
    )]
    fn from_word(&self) -> Option<Cow<'_, Callable>> {
        self.from_word.as_ref().map(Cow::Borrowed).or_else(|| {
            if let Data::Enum(ref variants) = self.base.data {
                // The first variant which has `word` set to `true`.
                // This assumes that validation has prevented multiple variants
                // from claiming `word`.
                let variant = variants
                    .iter()
                    .find(|v| v.word.map(|x| *x).unwrap_or_default())?;
                let variant_ident = &variant.ident;
                let closure: syn::ExprClosure = parse_quote! {
                    || ::darling::export::Ok(Self::#variant_ident)
                };
                Some(Cow::Owned(Callable::from(closure)))
            } else {
                None
            }
        })
    }
}

impl ParseAttribute for FromMetaOptions {
    fn parse_nested(&mut self, mi: &syn::Meta) -> Result<()> {
        let path = mi.path();

        if path.is_ident("from_word") {
            if self.from_word.is_some() {
                return Err(Error::duplicate_field_path(path).with_span(path));
            }

            self.from_word = FromMeta::from_meta(mi).map(Some)?;
        } else if path.is_ident("from_none") {
            if self.from_none.is_some() {
                return Err(Error::duplicate_field_path(path).with_span(path));
            }

            self.from_none = FromMeta::from_meta(mi).map(Some)?;
        } else {
            self.base.parse_nested(mi)?;
        }

        Ok(())
    }
}

impl ParseData for FromMetaOptions {
    fn parse_variant(&mut self, variant: &syn::Variant) -> Result<()> {
        self.base.parse_variant(variant)
    }

    fn parse_field(&mut self, field: &syn::Field) -> Result<()> {
        self.base.parse_field(field)
    }

    fn validate_body(&self, errors: &mut Accumulator) {
        self.base.validate_body(errors);

        match self.base.data {
            Data::Struct(ref data) => {
                if let Some(from_word) = &self.from_word {
                    if data.is_unit() {
                        errors.push(Error::custom("`from_word` cannot be used on unit structs because it conflicts with the generated impl").with_span(from_word));
                    } else if data.is_newtype() {
                        errors.push(Error::custom("`from_word` cannot be used on newtype structs because the implementation is entirely delegated to the inner type").with_span(from_word));
                    }
                }
            }
            Data::Enum(ref data) => {
                let word_variants: Vec<_> = data
                    .iter()
                    .filter_map(|variant| variant.word.as_ref())
                    .collect();

                if !word_variants.is_empty() {
                    if let Some(from_word) = &self.from_word {
                        errors.push(
                            Error::custom(
                                "`from_word` cannot be used with an enum that also uses `word`",
                            )
                            .with_span(from_word),
                        )
                    }
                }

                // Adds errors for duplicate `#[darling(word)]` annotations across all variants.
                if word_variants.len() > 1 {
                    for word in word_variants {
                        errors.push(
                            Error::custom("`#[darling(word)]` can only be applied to one variant")
                                .with_span(&word.span()),
                        );
                    }
                }
            }
        }
    }
}

impl<'a> From<&'a FromMetaOptions> for FromMetaImpl<'a> {
    fn from(v: &'a FromMetaOptions) -> Self {
        FromMetaImpl {
            base: (&v.base).into(),
            from_word: v.from_word(),
            from_none: v.from_none.as_ref(),
        }
    }
}

impl ToTokens for FromMetaOptions {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        FromMetaImpl::from(self).to_tokens(tokens)
    }
}