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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
use std::ops::Deref;

use quote::ToTokens;
use proc_macro2::TokenStream;
use syn::{self, Member, Index, punctuated::Punctuated, spanned::Spanned};

use crate::derived::{Derived, Struct, Variant, Union};
use crate::ItemInput;

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

impl<'p> FieldParent<'p> {
    pub fn input(&self) -> &ItemInput {
        match self {
            FieldParent::Variant(v) => v.parent.parent,
            FieldParent::Struct(v) => v.parent,
            FieldParent::Union(v) => v.parent,
        }
    }

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

impl ToTokens for FieldParent<'_> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        match self {
            FieldParent::Variant(v) => v.to_tokens(tokens),
            FieldParent::Struct(v) => v.to_tokens(tokens),
            FieldParent::Union(v) => v.to_tokens(tokens),
        }
    }
}

#[derive(Debug, Copy, Clone)]
pub(crate) enum FieldsKind<'p> {
    Named(&'p syn::FieldsNamed),
    Unnamed(&'p syn::FieldsUnnamed),
    Unit
}

impl<'a> From<&'a syn::Fields> for FieldsKind<'a> {
    fn from(fields: &'a syn::Fields) -> Self {
        match fields {
            syn::Fields::Named(fs) => FieldsKind::Named(&fs),
            syn::Fields::Unnamed(fs) => FieldsKind::Unnamed(&fs),
            syn::Fields::Unit => FieldsKind::Unit,
        }
    }
}

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

impl<'p> From<Variant<'p>> for Fields<'p> {
    fn from(v: Variant<'p>) -> Self {
        Fields { parent: FieldParent::Variant(v), kind: (&v.inner.fields).into() }
    }
}

impl<'p> From<Struct<'p>> for Fields<'p> {
    fn from(v: Struct<'p>) -> Self {
        Fields { parent: FieldParent::Struct(v), kind: (&v.inner.fields).into() }
    }
}

impl<'p> From<Union<'p>> for Fields<'p> {
    fn from(v: Union<'p>) -> Self {
        Fields { parent: FieldParent::Union(v), kind: FieldsKind::Named(&v.inner.fields) }
    }
}

impl<'f> Fields<'f> {
    fn fields(&self) -> Option<&'f Punctuated<syn::Field, syn::token::Comma>> {
        match self.kind {
            FieldsKind::Named(i) => Some(&i.named),
            FieldsKind::Unnamed(i) => Some(&i.unnamed),
            FieldsKind::Unit => None
        }
    }

    pub fn iter(self) -> impl Iterator<Item = Field<'f>> + Clone {
        self.fields()
            .into_iter()
            .flat_map(|fields| fields.iter())
            .enumerate()
            .map(move |(index, field)| Field {
                index,
                field: Derived::from(field, self.parent),
            })
    }

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

    pub fn count(self) -> usize {
        self.fields().map(|f| f.len()).unwrap_or(0)
    }

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

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

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

    fn surround(self, tokens: TokenStream) -> TokenStream {
        match self.kind {
            FieldsKind::Named(..) => quote_spanned!(self.span() => { #tokens }),
            FieldsKind::Unnamed(..) => quote_spanned!(self.span() => ( #tokens )),
            FieldsKind::Unit => quote!()
        }
    }

    pub fn match_tokens(self) -> TokenStream {
        // 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),*))
    }

    pub fn builder<F: Fn(Field) -> TokenStream>(&self, f: F) -> TokenStream {
        match self.parent {
            FieldParent::Struct(s) => s.builder(f),
            FieldParent::Variant(v) => v.builder(f),
            FieldParent::Union(_) => panic!("unions are not supported")
        }
    }
}

impl<'a> ToTokens for Fields<'a> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        match self.kind {
            FieldsKind::Named(v) => v.to_tokens(tokens),
            FieldsKind::Unnamed(v) => v.to_tokens(tokens),
            FieldsKind::Unit => tokens.extend(quote_spanned!(self.parent.span() => ()))
        }
    }
}

#[derive(Debug, Copy, Clone)]
pub struct Field<'f> {
    pub field: Derived<'f, syn::Field, FieldParent<'f>>,
    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) -> TokenStream {
        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, FieldParent<'f>>;

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

impl<'f> ToTokens for Field<'f> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        self.field.to_tokens(tokens)
    }
}