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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
use std::ops::Deref;

use syn::{self, Member, Index, punctuated::Punctuated};
use proc_macro::Span;
use proc_macro2::TokenStream as TokenStream2;

use derived::Derived;
use spanned::Spanned;

#[derive(Debug, Copy, Clone)]
pub enum FieldParent<'p> {
    Variant(Derived<'p, syn::Variant>),
    Struct(Derived<'p, syn::DataStruct>),
    Union(Derived<'p, syn::DataUnion>),
}

impl<'p> FieldParent<'p> {
    pub fn input(self) -> &'p syn::DeriveInput {
        match self {
            FieldParent::Variant(v) => v.derive_input,
            FieldParent::Struct(s) => s.derive_input,
            FieldParent::Union(u) => u.derive_input,
        }
    }

    pub fn fields(self) -> Fields<'p> {
        let (mut span, kind) = match self {
            FieldParent::Variant(v) => (v.fields.span(), (&v.value.fields).into()),
            FieldParent::Struct(s) => (s.fields.span(), (&s.value.fields).into()),
            FieldParent::Union(u) => (u.fields.span(), FieldKind::Named(&u.value.fields.named)),
        };

        if let FieldKind::Unit = kind {
            span = match self {
                FieldParent::Variant(v) => v.span(),
                _ => self.input().span(),
            };
        }

        Fields { parent: self, kind, span }
    }

    pub fn attrs(self) -> &'p [syn::Attribute] {
        match self {
            FieldParent::Variant(v) => &v.value.attrs,
            FieldParent::Struct(_) | FieldParent::Union(_) => &self.input().attrs,
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum FieldKind<'p> {
    Named(&'p Punctuated<syn::Field, syn::token::Comma>),
    Unnamed(&'p Punctuated<syn::Field, syn::token::Comma>),
    Unit
}

impl<'a> From<&'a syn::Fields> for FieldKind<'a> {
    fn from(syn_fields: &'a syn::Fields) -> Self {
        match syn_fields {
            syn::Fields::Named(ref fs) => FieldKind::Named(&fs.named),
            syn::Fields::Unnamed(ref fs) => FieldKind::Unnamed(&fs.unnamed),
            syn::Fields::Unit => FieldKind::Unit,
        }
    }
}

impl<'p> FieldKind<'p> {
    fn fields(&self) -> Option<&'p Punctuated<syn::Field, syn::token::Comma>> {
        match self {
            FieldKind::Named(inner) | FieldKind::Unnamed(inner) => Some(inner),
            FieldKind::Unit => None
        }
    }

    fn iter(self) -> impl Iterator<Item = &'p syn::Field> {
        self.fields().into_iter().flat_map(|fields| fields.iter())
    }
}

#[derive(Debug, Copy, Clone)]
pub struct Fields<'p> {
    pub(crate) parent: FieldParent<'p>,
    pub(crate) kind: FieldKind<'p>,
    pub(crate) span: Span,
}

impl<'f> Fields<'f> {
    pub fn iter(self) -> impl Iterator<Item = Field<'f>> {
        self.kind.iter().enumerate().map(move |(index, field)| Field {
            index,
            parent: self.parent,
            field: Derived::from(self.parent.input(), field),
        })
    }

    pub fn is_empty(self) -> bool {
        self.count() == 0
    }

    pub fn count(self) -> usize {
        match self.kind {
            FieldKind::Named(fields) => fields.len(),
            FieldKind::Unnamed(fields) => fields.len(),
            FieldKind::Unit => 0
        }
    }

    pub fn parent_attrs(self) -> &'f [syn::Attribute] {
        self.parent.attrs()
    }

    pub fn are_named(self) -> bool {
        match self.kind {
            FieldKind::Named(..) => true,
            _ => false
        }
    }

    pub fn are_unnamed(self) -> bool {
        match self.kind {
            FieldKind::Unnamed(..) => true,
            _ => false
        }
    }

    pub fn are_unit(self) -> bool {
        match self.kind {
            FieldKind::Unit => true,
            _ => false
        }
    }

    pub(crate) fn surround(self, tokens: TokenStream2) -> TokenStream2 {
        match self.kind {
            FieldKind::Named(..) => quote!({ #tokens }),
            FieldKind::Unnamed(..) => quote!(( #tokens )),
            FieldKind::Unit => quote!()
        }
    }

    pub fn match_tokens(self) -> TokenStream2 {
        // This relies on match ergonomics to work in either case.
        let idents = self.iter().map(|field| {
            let match_ident = field.match_ident();
            match field.ident {
                Some(ref id) => quote!(#id: #match_ident),
                None => quote!(#match_ident)
            }

        });

        self.surround(quote!(#(#idents),*))
    }
}

impl<'f> Spanned for Fields<'f> {
    fn span(&self) -> Span {
        self.span
    }
}

#[derive(Debug, Copy, Clone)]
pub struct Field<'f> {
    pub parent: FieldParent<'f>,
    pub field: Derived<'f, syn::Field>,
    pub index: usize,
}

impl<'f> Field<'f> {
    pub fn match_ident(self) -> syn::Ident {
        let name = match self.ident {
            Some(ref id) => format!("__{}", id),
            None => format!("__{}", self.index)
        };

        syn::Ident::new(&name, self.span().into())
    }

    pub fn accessor(&self) -> TokenStream2 {
        if let FieldParent::Variant(_) = self.parent {
            let ident = self.match_ident();
            quote!(#ident)
        } else {
            let span = self.field.span().into();
            let member = match self.ident {
                Some(ref ident) => Member::Named(ident.clone()),
                None => Member::Unnamed(Index { index: self.index as u32, span })
            };

            quote_spanned!(span => self.#member)
        }
    }
}

impl<'f> Deref for Field<'f> {
    type Target = Derived<'f, syn::Field>;

    fn deref(&self) -> &Self::Target {
        &self.field
    }
}