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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
use proc_macro2::{Ident, Span, TokenStream};
use quote::{quote, ToTokens};
use std::{collections::HashMap, error};
use syn::{parse_quote, visit_mut::VisitMut, Arm, Data, DeriveInput, GenericParam, LitStr, Stmt};

use crate::{
    fields_to_structure_fields, generic_param_to_generic_argument_token_stream,
    generic_parameters_have_same_name, BuildPair, Field, Fields, PrefixAndPostfix, Structure,
    Trait, TraitMethod,
};

pub type StructureHandlerResult = Result<PrefixAndPostfix<Stmt>, Box<dyn error::Error>>;
pub type FieldHandlerResult = Result<Vec<Stmt>, Box<dyn error::Error>>;

/// Generates implementation for a trait over a structure
/// - Generated impl blocks
/// - Handles patterns for read and unread fields
pub fn build_implementation_over_structure<'a>(
    structure: &'a DeriveInput,
    implementing_trait: Trait,
    structure_handler: impl Fn(String, &'a DeriveInput) -> StructureHandlerResult,
    field_handler: impl for<'b> Fn(String, &'b mut Fields<'a>) -> FieldHandlerResult,
) -> TokenStream {
    let structure_name = &structure.ident;

    // Cloning as modify clashes
    let mut structure_generics = structure.generics.clone();

    let Trait {
        name: trait_name,
        generic_parameters: trait_generic_parameters,
        methods: trait_methods,
    } = implementing_trait;

    let mut conflicts_map = HashMap::new();

    let trait_with_arguments: TokenStream = if !trait_generic_parameters.is_empty() {
        // Rename clashing trait names
        if structure_generics.lt_token.is_some() {
            for structure_generic_parameter in structure_generics.params.iter_mut() {
                let collision = trait_generic_parameters
                    .iter()
                    .any(|trait_generic_parameter| {
                        generic_parameters_have_same_name(
                            trait_generic_parameter,
                            structure_generic_parameter,
                        )
                    });

                if collision {
                    // Just hope nothing called `_gp...`...
                    let new_ident =
                        Ident::new(&format!("_gp{}", conflicts_map.len()), Span::call_site());

                    let ident: &mut Ident = match structure_generic_parameter {
                        GenericParam::Type(gtp) => &mut gtp.ident,
                        GenericParam::Lifetime(glp) => &mut glp.lifetime.ident,
                        GenericParam::Const(gcp) => &mut gcp.ident,
                    };
                    conflicts_map.insert(ident.clone(), new_ident.clone());
                    *ident = new_ident;
                }
            }
        }

        // Removes bounds off parameters thus becoming arguments
        let trait_generic_arguments =
            trait_generic_parameters
                .iter()
                .map(|trait_generic_parameter| {
                    generic_param_to_generic_argument_token_stream(trait_generic_parameter)
                });

        quote!(#trait_name<#(#trait_generic_arguments),*>)
    } else {
        trait_name.to_token_stream()
    };

    // Combination of structure and trait generics, retains bounds
    let generics_for_impl =
        if !trait_generic_parameters.is_empty() || !structure_generics.params.is_empty() {
            let mut references = trait_generic_parameters
                .iter()
                .chain(structure_generics.params.iter())
                .collect::<Vec<_>>();

            // This is the order in which the AST is defined
            references.sort_unstable_by_key(|generic| match generic {
                GenericParam::Lifetime(_) => 0,
                GenericParam::Type(_) => 1,
                GenericParam::Const(_) => 2,
            });

            Some(quote!(<#(#references),*>))
        } else {
            None
        };

    // Could be `HashSet` but Rust tolerates duplicate where clause (when that rarely occurs)
    // Vec ensures consistent order which makes tests easy
    let mut where_clauses = Vec::new();

    match &structure.data {
        Data::Struct(r#struct) => {
            let methods = trait_methods
                .into_iter()
                .flat_map(|method| {
                    let TraitMethod {
                        method_name,
                        method_parameters,
                        method_generics,
                        return_type,
                        build_pair,
                    } = method;

                    let structure_result = structure_handler(method_name.to_string(), structure);

                    let PrefixAndPostfix { prefix, postfix } = match structure_result {
                        Ok(structure) => structure,
                        Err(err) => {
                            let error_as_string = LitStr::new(&err.to_string(), Span::call_site());
                            return quote!( compile_error!(#error_as_string); )
                        },
                    };

                    let mut fields = fields_to_structure_fields(
                        &r#struct.fields,
                        Structure::Struct {
                            struct_name: structure_name,
                            struct_attrs: &structure.attrs,
                        },
                    );

                    let body = match field_handler(method_name.to_string(), &mut fields) {
                        Ok(body) => body,
                        Err(err) => {
                            let error_as_string = LitStr::new(
                                &err.to_string(),
                                Span::call_site(),
                            );
                            return quote!( compile_error!(#error_as_string); )
                        },
                    };

                    where_clauses.extend(fields.fields_iterator().flat_map(|field| field.get_type_that_needs_constraint()));

                    let self_path = parse_quote!(Self);
                    let matcher = fields.to_pattern(&self_path, crate::Variant::Primary);
                    let locals = if build_pair.is_pair() {
                        let alternative_matcher = fields.to_pattern(&self_path, crate::Variant::Secondary);

                        quote! {
                            let #matcher = self;
                            let #alternative_matcher = other
                        }
                    } else {
                        quote!(let #matcher = self)
                    };

                    // If there are generic parameter, wrap in them in '<' '>'
                    let chevroned_generic_params = if !method_generics.is_empty() {
                        Some(quote!(<#(#method_generics),*>))
                    } else {
                        None
                    };

                    let return_type = return_type.iter();

                    quote! {
                        fn #method_name#chevroned_generic_params(#(#method_parameters),*) #(-> #return_type)* {
                            #(#prefix)*
                            #locals;
                            #(#body)*
                            #(#postfix)*
                        }
                    }
                })
                .collect::<TokenStream>();

            let where_clause: Option<_> = if !where_clauses.is_empty() {
                if !conflicts_map.is_empty() {
                    for element in where_clauses.iter_mut() {
                        RenameGenerics(&conflicts_map).visit_type_mut(element)
                    }
                }
                Some(quote!(where #( #where_clauses: #trait_with_arguments ),* ))
            } else {
                None
            };

            quote! {
                impl #generics_for_impl #trait_with_arguments for #structure_name #structure_generics #where_clause {
                    #methods
                }
            }
        }
        Data::Enum(r#enum) => {
            let methods = trait_methods
                .into_iter()
                .flat_map(|method| {
                    let TraitMethod {
                        method_name,
                        method_parameters,
                        method_generics,
                        return_type,
                        build_pair,
                    } = method;

                    let structure_result = structure_handler(method_name.to_string(), structure);

                    let PrefixAndPostfix { prefix, postfix } = match structure_result {
                        Ok(structure) => structure,
                        Err(err) => {
                            let error_as_string = LitStr::new(&err.to_string(), Span::call_site());
                            return quote!( compile_error!(#error_as_string); );
                        }
                    };

                    let branches = r#enum.variants.iter().map(|variant| {
                        let variant_ident = &variant.ident;
                        let mut fields = fields_to_structure_fields(
                            &variant.fields,
                            Structure::EnumVariant {
                                enum_name: structure_name,
                                enum_attrs: &structure.attrs,
                                variant_name: variant_ident,
                                variant_attrs: &variant.attrs,
                            },
                        );

                        let handler_result = field_handler(method_name.to_string(), &mut fields);

                        let body = match handler_result {
                            Ok(body) => body,
                            Err(err) => {
                                let error_as_string =
                                    LitStr::new(&err.to_string(), Span::call_site());

                                return quote!( compile_error!(#error_as_string); );
                            }
                        };

                        where_clauses.extend(fields.fields_iterator().flat_map(|field| field.get_type_that_needs_constraint()));

                        let variant_pattern = parse_quote!(Self::#variant_ident);
                        let matcher = fields.to_pattern(&variant_pattern, crate::Variant::Primary);

                        if build_pair.is_pair() {
                            let alternative_matcher = fields.to_pattern(&variant_pattern, crate::Variant::Secondary);

                            quote! ( (#matcher, #alternative_matcher) => { #(#body)* } )                           
                        } else {
                            quote! { #matcher => { #(#body)* } }
                        }
                    });

                    let (exhaustive_arm, matching_on): (Option<Arm>, TokenStream) = if let BuildPair::Pair {
                        ref statements_if_enums_do_not_match,
                        ref other_item_name
                    } = build_pair
                    {
                        let arm = Some(parse_quote! { _ => {
                            #(#statements_if_enums_do_not_match)*
                        }});
                        (arm, quote! { (self, #other_item_name) })
                    } else {
                        (None, quote!(self))
                    };

                    // If there are generic parameter, wrap in them in `<..>`
                    let chevroned_generic_params = if !method_generics.is_empty() {
                        Some(quote!(<#(#method_generics),*>))
                    } else {
                        None
                    };

                    let return_type = return_type.iter();

                    quote! {
                        fn #method_name#chevroned_generic_params(#(#method_parameters),*) #(-> #return_type)* {
                            #(#prefix)*
                            match #matching_on {
                                #(#branches),*,
                                #exhaustive_arm
                            }
                            #(#postfix)*
                        }
                    }
                })
                .collect::<TokenStream>();

            let where_clause: Option<_> = if !where_clauses.is_empty() {
                if !conflicts_map.is_empty() {
                    for element in where_clauses.iter_mut() {
                        RenameGenerics(&conflicts_map).visit_type_mut(element)
                    }
                }
                Some(quote!(where #( #where_clauses : #trait_with_arguments ),*))
            } else {
                None
            };

            quote! {
                impl#generics_for_impl #trait_with_arguments for #structure_name #structure_generics #where_clause {
                    #methods
                }
            }
        }
        Data::Union(_) => {
            quote!( compile_error!("syn-helpers does not support derives on unions"); )
        }
    }
}

struct RenameGenerics<'a>(pub &'a HashMap<Ident, Ident>);

impl<'a> VisitMut for RenameGenerics<'a> {
    fn visit_type_reference_mut(&mut self, i: &mut syn::TypeReference) {
        if let Some(ref mut lifetime) = i.lifetime {
            if let Some(rewrite) = self.0.get(&lifetime.ident).cloned() {
                lifetime.ident = rewrite;
            }
        }
        self.visit_type_mut(&mut i.elem);
    }

    fn visit_type_path_mut(&mut self, i: &mut syn::TypePath) {
        if let Some(current_ident) = i.path.get_ident() {
            if let Some(rewrite) = self.0.get(current_ident).cloned() {
                i.path = rewrite.into();
            }
        }
    }
}