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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
// Rust language amplification derive library providing multiple generic trait
// implementations, type wrappers, derive macros and other language enhancements
//
// Written in 2019-2021 by
//     Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the MIT License
// along with this software.
// If not, see <https://opensource.org/licenses/MIT>.

// TODO: Write docs for `data` module
#![allow(missing_docs)]

use std::ops::{Deref, DerefMut};
use std::slice;

use proc_macro2::{Ident, Span, TokenStream as TokenStream2};
use quote::ToTokens;
use syn::{DeriveInput, Generics, Path};

use crate::{ident, ParametrizedAttr};

#[derive(Clone)]
pub struct DataType {
    pub generics: Generics,
    pub name: Ident,
    pub attr: ParametrizedAttr,
    pub inner: DataInner,
}

#[derive(Clone)]
pub enum DataInner {
    Uninhabited,
    Struct(Fields),
    Enum(Items<Variant>),
    Union(Items<NamedField>),
}

#[derive(Clone)]
pub enum Fields {
    Unit,
    Named(Items<NamedField>),
    Unnamed(Items<Field>),
}

#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum FieldKind {
    Named,
    Unnamed,
}

#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum EnumKind {
    Primitive,
    Associated,
}

impl Fields {
    pub fn is_unit(&self) -> bool { matches!(self, Fields::Unit) }

    pub fn kind(&self) -> FieldKind {
        match self {
            Fields::Unit => FieldKind::Unnamed,
            Fields::Named(_) => FieldKind::Named,
            Fields::Unnamed(_) => FieldKind::Unnamed,
        }
    }
}

pub trait Element: Sized {
    type Input: Sized;
    fn with(input: Self::Input, attr_name: &Ident) -> syn::Result<Self>;
}

#[derive(Clone)]
pub struct Items<E: Element>(Vec<E>);

impl<E: Element> Deref for Items<E> {
    type Target = Vec<E>;
    fn deref(&self) -> &Self::Target { &self.0 }
}

impl<E: Element> DerefMut for Items<E> {
    fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
}

impl<'a, E: Element> IntoIterator for &'a Items<E> {
    type Item = &'a E;
    type IntoIter = slice::Iter<'a, E>;

    fn into_iter(self) -> Self::IntoIter { self.0.iter() }
}

impl Items<Variant> {
    pub fn enum_kind(&self) -> EnumKind {
        if self.iter().all(|var| var.fields.is_unit()) {
            EnumKind::Primitive
        } else {
            EnumKind::Associated
        }
    }
}

#[derive(Clone)]
pub struct NamedField {
    pub name: Ident,
    pub field: Field,
}

#[derive(Clone)]
pub struct Field {
    pub vis: Vis,
    pub attr: ParametrizedAttr,
    pub ty: syn::Type,
}

#[derive(Clone)]
pub struct Variant {
    pub attr: ParametrizedAttr,
    pub name: Ident,
    pub fields: Fields,
}

#[derive(Clone)]
pub enum Vis {
    Public,
    Scoped(Scope),
    Inherited,
}

#[derive(Clone)]
pub enum Scope {
    Crate,
    Super,
    Path(Path),
}

impl DataType {
    pub fn with(input: DeriveInput, attr_name: Ident) -> syn::Result<Self> {
        let attr = ParametrizedAttr::with(attr_name.to_string(), input.attrs.as_ref())?;
        Ok(DataType {
            generics: input.generics,
            name: input.ident,
            attr,
            inner: DataInner::with(input.data, &attr_name)?,
        })
    }
}

impl DataInner {
    pub fn with(data: syn::Data, attr_name: &Ident) -> syn::Result<Self> {
        match data {
            syn::Data::Struct(inner) => {
                Fields::with(inner.fields, attr_name).map(DataInner::Struct)
            }
            syn::Data::Enum(inner) if inner.variants.is_empty() => Ok(DataInner::Uninhabited),
            syn::Data::Enum(inner) => {
                Items::with(inner.variants.into_iter(), attr_name).map(DataInner::Enum)
            }
            syn::Data::Union(inner) => {
                Items::with(inner.fields.named.into_iter(), attr_name).map(DataInner::Union)
            }
        }
    }
}

impl Fields {
    pub fn with(fields: syn::Fields, attr_name: &Ident) -> syn::Result<Self> {
        match fields {
            syn::Fields::Named(fields) => {
                Items::with(fields.named.into_iter(), attr_name).map(Fields::Named)
            }
            syn::Fields::Unnamed(fields) => {
                Items::with(fields.unnamed.into_iter(), attr_name).map(Fields::Unnamed)
            }
            syn::Fields::Unit => Ok(Fields::Unit),
        }
    }
}

impl<E: Element> Items<E> {
    pub fn with(
        items: impl ExactSizeIterator<Item = E::Input>,
        attr_name: &Ident,
    ) -> syn::Result<Self> {
        let mut list = Vec::with_capacity(items.len());
        for el in items {
            list.push(E::with(el, attr_name)?)
        }
        Ok(Items(list))
    }
}

impl Element for NamedField {
    type Input = syn::Field;

    fn with(input: Self::Input, attr_name: &Ident) -> syn::Result<Self> {
        Ok(NamedField {
            name: input.ident.clone().expect("named field without a name"),
            field: Field::with(input, attr_name)?,
        })
    }
}
impl Element for Field {
    type Input = syn::Field;

    fn with(input: Self::Input, attr_name: &Ident) -> syn::Result<Self> {
        let attr = ParametrizedAttr::with(attr_name.to_string(), input.attrs.as_ref())?;
        Ok(Field {
            vis: input.vis.into(),
            attr,
            ty: input.ty,
        })
    }
}

impl Element for Variant {
    type Input = syn::Variant;

    fn with(input: Self::Input, attr_name: &Ident) -> syn::Result<Self> {
        let attr = ParametrizedAttr::with(attr_name.to_string(), input.attrs.as_ref())?;
        Ok(Variant {
            attr,
            name: input.ident,
            fields: Fields::with(input.fields, attr_name)?,
        })
    }
}

impl From<syn::Visibility> for Vis {
    fn from(vis: syn::Visibility) -> Self {
        match vis {
            syn::Visibility::Public(_) => Vis::Public,
            syn::Visibility::Crate(_) => Vis::Scoped(Scope::Crate),
            syn::Visibility::Restricted(scope) => Vis::Scoped(scope.into()),
            syn::Visibility::Inherited => Vis::Inherited,
        }
    }
}

impl From<syn::VisRestricted> for Scope {
    fn from(scope: syn::VisRestricted) -> Self {
        if scope.in_token.is_none() {
            debug_assert_eq!(scope.path.get_ident().unwrap(), &ident!(super));
            Scope::Super
        } else {
            Scope::Path(*scope.path)
        }
    }
}

impl DataType {
    pub fn derive<D: DeriveInner>(
        &self,
        trait_crate: &Path,
        trait_name: &Ident,
        attr: &D,
    ) -> syn::Result<TokenStream2> {
        let (impl_generics, ty_generics, where_clause) = self.generics.split_for_impl();

        let ident_name = &self.name;

        let inner = match &self.inner {
            DataInner::Struct(Fields::Unit) => attr.derive_unit_inner(),
            DataInner::Struct(Fields::Unnamed(fields)) => attr.derive_tuple_inner(fields),
            DataInner::Struct(Fields::Named(fields)) => attr.derive_struct_inner(fields),
            DataInner::Enum(variants) => attr.derive_enum_inner(variants),
            DataInner::Union(_) => Err(syn::Error::new(
                Span::call_site(),
                format!(
                    "deriving `{}` is not supported in unions",
                    trait_name.to_token_stream().to_string()
                ),
            )),
            DataInner::Uninhabited => Err(syn::Error::new(
                Span::call_site(),
                format!(
                    "deriving `{}` is not supported for uninhabited enums",
                    trait_name.to_token_stream().to_string()
                ),
            )),
        }?;

        let tokens = quote! {
            #[automatically_derived]
            impl #impl_generics #trait_crate::#trait_name for #ident_name #ty_generics #where_clause {
                #inner
            }
        };

        Ok(tokens)
    }
}

pub trait DeriveInner {
    fn derive_unit_inner(&self) -> syn::Result<TokenStream2>;
    fn derive_struct_inner(&self, fields: &Items<NamedField>) -> syn::Result<TokenStream2>;
    fn derive_tuple_inner(&self, fields: &Items<Field>) -> syn::Result<TokenStream2>;
    fn derive_enum_inner(&self, fields: &Items<Variant>) -> syn::Result<TokenStream2>;
}