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
use std::borrow::Cow;

use crate::ast::Fields;
use crate::codegen;
use crate::options::{Core, InputField, ParseAttribute};
use crate::util::SpannedValue;
use crate::{Error, FromMeta, Result};

#[derive(Debug, Clone)]
pub struct InputVariant {
    ident: syn::Ident,
    attr_name: Option<String>,
    data: Fields<InputField>,
    skip: Option<bool>,
    /// Whether or not the variant should be used to create an instance for
    /// `FromMeta::from_word`.
    pub word: Option<SpannedValue<bool>>,
    /// Whether or not unknown fields are acceptable in this
    allow_unknown_fields: Option<bool>,
}

impl InputVariant {
    pub fn as_codegen_variant<'a>(&'a self, ty_ident: &'a syn::Ident) -> codegen::Variant<'a> {
        codegen::Variant {
            ty_ident,
            variant_ident: &self.ident,
            name_in_attr: self
                .attr_name
                .as_ref()
                .map_or_else(|| Cow::Owned(self.ident.to_string()), Cow::Borrowed),
            data: self.data.as_ref().map(InputField::as_codegen_field),
            skip: self.skip.unwrap_or_default(),
            word: *self.word.unwrap_or_default(),
            allow_unknown_fields: self.allow_unknown_fields.unwrap_or_default(),
        }
    }

    pub fn from_variant(v: &syn::Variant, parent: Option<&Core>) -> Result<Self> {
        let mut starter = (InputVariant {
            ident: v.ident.clone(),
            attr_name: Default::default(),
            data: Fields::empty_from(&v.fields),
            skip: Default::default(),
            word: Default::default(),
            allow_unknown_fields: None,
        })
        .parse_attributes(&v.attrs)?;

        starter.data.fields = match v.fields {
            syn::Fields::Unit => vec![],
            syn::Fields::Unnamed(ref fields) => {
                let mut items = Vec::with_capacity(fields.unnamed.len());
                for item in &fields.unnamed {
                    items.push(InputField::from_field(item, parent)?);
                }

                items
            }
            syn::Fields::Named(ref fields) => {
                let mut items = Vec::with_capacity(fields.named.len());
                for item in &fields.named {
                    items.push(InputField::from_field(item, parent)?);
                }

                items
            }
        };

        Ok(if let Some(p) = parent {
            starter.with_inherited(p)
        } else {
            starter
        })
    }

    fn with_inherited(mut self, parent: &Core) -> Self {
        if self.attr_name.is_none() {
            self.attr_name = Some(parent.rename_rule.apply_to_variant(self.ident.to_string()));
        }

        if self.allow_unknown_fields.is_none() {
            self.allow_unknown_fields = Some(parent.allow_unknown_fields.unwrap_or_default());
        }

        self
    }
}

impl ParseAttribute for InputVariant {
    fn parse_nested(&mut self, mi: &syn::Meta) -> Result<()> {
        let path = mi.path();
        if path.is_ident("rename") {
            if self.attr_name.is_some() {
                return Err(Error::duplicate_field_path(path).with_span(mi));
            }

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

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

            if !self.data.is_unit() {
                let note = "`#[darling(word)]` can only be applied to a unit variant";
                #[cfg(feature = "diagnostics")]
                let error = Error::unknown_field_path(path).note(note);
                #[cfg(not(feature = "diagnostics"))]
                let error = Error::custom(format!("Unexpected field: `word`. {}", note));

                return Err(error.with_span(mi));
            }

            self.word = FromMeta::from_meta(mi)?;
        } else {
            return Err(Error::unknown_field_path(path).with_span(mi));
        }

        Ok(())
    }
}