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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
//! See the docs for "diesel-factories" for more info about this.

#![deny(mutable_borrow_reservation_conflict)]
#![recursion_limit = "128"]
#![deny(
    mutable_borrow_reservation_conflict,
    missing_debug_implementations,
    missing_copy_implementations,
    trivial_casts,
    trivial_numeric_casts,
    unsafe_code,
    unstable_features,
    unused_import_braces,
    unused_qualifications
)]

use heck::CamelCase;
use proc_macro2::{Span, TokenStream};
use quote::quote;
use quote::{format_ident, ToTokens};
use syn::spanned::Spanned;
use syn::{
    parse::{Parse, ParseStream},
    parse_macro_input,
    punctuated::Punctuated,
    GenericArgument, Ident, ItemStruct, Lifetime, Path, PathArguments, PathSegment, Token, Type,
};

#[proc_macro_derive(Factory, attributes(factory))]
pub fn derive_factory(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = parse_macro_input!(input as Input);
    let tokens = quote! { #input };
    proc_macro::TokenStream::from(tokens)
}

mod struct_attr {
    use bae::FromAttributes;
    use syn::{Ident, Path, Type};

    #[derive(Debug, FromAttributes)]
    pub struct Factory {
        pub model: Type,
        pub table: Path,
        pub connection: Option<Type>,
        pub id: Option<Type>,
        pub id_name: Option<Ident>,
    }
}

mod field_attr {
    use bae::FromAttributes;
    use syn::Ident;

    #[derive(Debug, FromAttributes)]
    pub struct Factory {
        pub foreign_key_name: Ident,
    }
}

#[derive(Debug)]
struct Input {
    model: Type,
    table: Path,
    connection: Type,
    id_type: Type,
    id_name: Ident,
    factory_name: Ident,
    fields: Vec<(Ident, Type)>,
    associations: Vec<(Ident, AssociationType, Ident)>,
    lifetime: Option<Lifetime>,
}

impl Parse for Input {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let ItemStruct {
            attrs,
            ident: factory_name,
            generics,
            fields: item_strut_fields,

            struct_token: _,
            semi_token: _,
            vis: _,
        } = input.parse::<ItemStruct>()?;

        let struct_attr::Factory {
            model,
            table,
            connection,
            id,
            id_name,
        } = struct_attr::Factory::from_attributes(&attrs)?;

        let connection =
            connection.unwrap_or_else(|| syn::parse2(quote! { diesel::pg::PgConnection }).unwrap());
        let id_type = id.unwrap_or_else(|| syn::parse2(quote! { i32 }).unwrap());
        let id_name = id_name.unwrap_or_else(|| syn::parse2(quote! { id }).unwrap());

        // parse fields and associations
        let mut fields = Vec::new();
        let mut associations = Vec::new();
        for field in item_strut_fields {
            let field_span = field.span();

            let name = field
                .ident
                .ok_or_else(|| syn::Error::new(field_span, "Unnamed fields are not supported"))?;

            let field_ty = field.ty.clone();

            if let Ok(association_type) = AssociationType::new(field_ty) {
                let foreign_key_name =
                    if let Some(attr) = field_attr::Factory::try_from_attributes(&field.attrs)? {
                        attr.foreign_key_name
                    } else {
                        format_ident!("{}_{}", name, id_name)
                    };

                associations.push((name, association_type, foreign_key_name));
            } else {
                if field_attr::Factory::from_attributes(&field.attrs).is_ok() {
                    return Err(syn::Error::new(
                        field_span,
                        "`#[factory]` attributes are only allowed on association fields",
                    ));
                }

                fields.push((name, field.ty));
            }
        }

        // parse generic lifetime
        let generics_span = generics.span();
        let mut generics_iter = generics.params.into_iter();
        let lifetime = match generics_iter.next() {
            Some(inner) => match inner {
                syn::GenericParam::Lifetime(lt_def) => {
                    if !lt_def.bounds.is_empty() {
                        return Err(syn::Error::new(lt_def.span(), "Unexpected lifetime bounds"));
                    }

                    Some(lt_def.lifetime)
                }
                _ => {
                    return Err(syn::Error::new(
                        generics_span,
                        "Expected a single generic lifetime argument",
                    ));
                }
            },
            None => None,
        };

        if let Some(arg) = generics_iter.next() {
            return Err(syn::Error::new(arg.span(), "Unexpected generic argument"));
        }

        Ok(Input {
            model,
            table,
            connection,
            id_type,
            id_name,
            factory_name,
            fields,
            associations,
            lifetime,
        })
    }
}

impl ToTokens for Input {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        tokens.extend(self.factory_trait_impl());
        tokens.extend(self.field_builder_methods());
        tokens.extend(self.association_builder_methods());
    }
}

impl Input {
    fn factory_trait_impl(&self) -> TokenStream {
        let factory = &self.factory_name;
        let lifetime = &self.lifetime;
        let model_type = &self.model;
        let id_type = &self.id_type;
        let connection_type = &self.connection;
        let table_path = &self.table;
        let id_name = &self.id_name;

        let insert_code = if self.no_fields() {
            quote! {
                diesel::insert_into(#table_path::table)
                    .default_values()
                    .get_result::<Self::Model>(con)
                    .expect("Insert of factory failed")
            }
        } else {
            let values = self.fields.iter().map(|(name, _)| {
                quote! { #table_path::#name.eq(&self.#name) }
            });
            let values = values.chain(self.associations.iter().map(
                |(name, association_type, foreign_key_field)| {
                    if association_type.is_optional {
                        quote! {
                            {
                                let value = self.#name.map(|inner| {
                                    inner.insert_returning_id(con)
                                });
                                #table_path::#foreign_key_field.eq(value)
                            }
                        }
                    } else {
                        quote! {
                            #table_path::#foreign_key_field.eq(self.#name.insert_returning_id(con))
                        }
                    }
                },
            ));

            quote! {
                let values = ( #(#values),* );
                diesel::insert_into(#table_path::table)
                    .values(values)
                    .get_result::<Self::Model>(con)
                    .expect("Insert of factory failed")
            }
        };

        quote! {
            impl <#lifetime> diesel_factories::Factory for #factory <#lifetime> {
                type Model = #model_type;
                type Id = #id_type;
                type Connection = #connection_type;

                fn insert(self, con: &Self::Connection) -> Self::Model {
                    use diesel::prelude::*;
                    #insert_code
                }

                fn id_for_model(model: &Self::Model) -> &Self::Id {
                    &model.#id_name
                }
            }
        }
    }

    fn no_fields(&self) -> bool {
        self.fields.is_empty() && self.associations.is_empty()
    }

    fn field_builder_methods(&self) -> TokenStream {
        let factory_name = &self.factory_name;

        let methods = self.fields.iter().map(|(field_name, ty)| {
            quote! {
                #[allow(missing_docs, dead_code)]
                pub fn #field_name(mut self, new: impl std::convert::Into<#ty>) -> Self {
                    self.#field_name = new.into();
                    self
                }
            }
        });

        let lifetime = &self.lifetime;

        quote! {
            impl <#lifetime> #factory_name <#lifetime> {
                #(#methods)*
            }
        }
    }

    fn association_builder_methods(&self) -> TokenStream {
        let factory_name = &self.factory_name;

        self.associations.iter().map(|(field_name, association_type, _)| {
            let association_name = format_ident!("{}", field_name.to_string().to_camel_case());
            let trait_name = format_ident!("Set{}On{}", association_name, factory_name);

            let lifetime = &association_type.lifetime;

            let model_type = &association_type.model_type;
            let other_factory = &association_type.factory_type;

            let model_impl = if association_type.is_optional {
                quote! {
                    impl<#lifetime> #trait_name<std::option::Option<& #lifetime #model_type>> for #factory_name<#lifetime> {
                        fn #field_name(mut self, t: std::option::Option<& #lifetime #model_type>) -> Self {
                            self.#field_name = t.map(diesel_factories::Association::new_model);
                            self
                        }
                    }
                }
            } else {
                quote! {
                    impl<#lifetime> #trait_name<& #lifetime #model_type> for #factory_name<#lifetime> {
                        fn #field_name(mut self, t: & #lifetime #model_type) -> Self {
                            self.#field_name = diesel_factories::Association::new_model(t);
                            self
                        }
                    }
                }
            };

            let factory_impl = if association_type.is_optional {
                quote! {
                    impl<#lifetime> #trait_name<std::option::Option<#other_factory>> for #factory_name<#lifetime> {
                        fn #field_name(mut self, t: std::option::Option<#other_factory>) -> Self {
                            self.#field_name = t.map(diesel_factories::Association::new_factory);
                            self
                        }
                    }
                }
            } else {
                quote! {
                    impl<#lifetime> #trait_name<#other_factory> for #factory_name<#lifetime> {
                        fn #field_name(mut self, t: #other_factory) -> Self {
                            self.#field_name = diesel_factories::Association::new_factory(t);
                            self
                        }
                    }
                }
            };

            quote! {
                #[allow(missing_docs, dead_code)]
                pub trait #trait_name<T> {
                    fn #field_name(self, t: T) -> Self;
                }

                #model_impl
                #factory_impl
            }
        }).collect()
    }
}

#[derive(Debug)]
struct AssociationType {
    span: Span,
    lifetime: Lifetime,
    model_type: Type,
    factory_type: Type,
    is_optional: bool,
}

impl AssociationType {
    fn new(ty: Type) -> syn::Result<Self> {
        let type_path = match ty {
            Type::Path(ty) => ty,
            _ => return Err(syn::Error::new(ty.span(), "Expected type path")),
        };

        let whole_span = type_path.span();

        if type_path.qself.is_some() {
            return Err(syn::Error::new(
                type_path.span(),
                "Qualified self types are not allowed here",
            ));
        }

        let segments = type_path.path.segments;
        let segments_span = segments.span();

        let (segments, is_optional) = peel_option(segments);
        let mut segments_iter = segments.into_iter().peekable();

        // skip fully qualified path
        let first = segments_iter
            .peek()
            .ok_or_else(|| syn::Error::new(segments_span, "Empty type path"))?;
        if first.ident == "diesel_factories" {
            segments_iter.next().ok_or_else(|| {
                syn::Error::new(
                    segments_span,
                    "Expected something after `diesel_factories::`",
                )
            })?;
        }

        let path_segment = segments_iter
            .next()
            .ok_or_else(|| syn::Error::new(segments_span, "Type path too short"))?;
        let arguments = if path_segment.ident == "Association" {
            path_segment.arguments
        } else {
            return Err(syn::Error::new(
                path_segment.span(),
                format!(
                    "Unexpected name `{}`. Expected `Association` or `diesel_factories::Association`",
                    path_segment.ident,
                )
            ));
        };

        let arguments = match arguments {
            syn::PathArguments::AngleBracketed(args) => args,
            syn::PathArguments::Parenthesized(inner) => {
                return Err(syn::Error::new(
                    inner.span(),
                    "Unexpected parenthesized type arguments. Expected angle bracketed arguments like `<...>`",
                ));
            }
            syn::PathArguments::None => {
                return Err(syn::Error::new(
                    whole_span,
                    "Missing association type arguments",
                ));
            }
        };

        if let Some(colon2) = &arguments.colon2_token {
            return Err(syn::Error::new(colon2.span(), "Unexpected `::`"));
        }

        let args_span = arguments.span();
        let mut args_iter = arguments.args.into_iter();

        let lifetime = match args_iter.next() {
            Some(inner) => match inner {
                syn::GenericArgument::Lifetime(lt) => lt,
                _ => {
                    return Err(syn::Error::new(
                        args_span,
                        "Expected generic lifetime argument",
                    ));
                }
            },
            None => {
                return Err(syn::Error::new(args_span, "Missing generic type arguments"));
            }
        };

        let model_type = match args_iter.next() {
            Some(inner) => match inner {
                syn::GenericArgument::Type(ty) => ty,
                _ => {
                    return Err(syn::Error::new(args_span, "Expected generic type argument"));
                }
            },
            None => {
                return Err(syn::Error::new(args_span, "Missing generic type arguments"));
            }
        };

        let factory_type = match args_iter.next() {
            Some(inner) => match inner {
                syn::GenericArgument::Type(ty) => ty,
                _ => {
                    return Err(syn::Error::new(args_span, "Expected generic type argument"));
                }
            },
            None => {
                return Err(syn::Error::new(args_span, "Missing generic type arguments"));
            }
        };

        if let Some(next) = args_iter.next() {
            return Err(syn::Error::new(next.span(), "Too many generic arguments"));
        }

        Ok(AssociationType {
            span: whole_span,
            lifetime,
            model_type,
            factory_type,
            is_optional,
        })
    }
}

fn peel_option(
    segments: Punctuated<PathSegment, Token![::]>,
) -> (Punctuated<PathSegment, Token![::]>, bool) {
    let original_segments = segments.clone();

    let things_inside_option = (move || {
        let mut iter = segments.into_iter();

        let first_segment = iter.next()?;

        let option_segment = if first_segment.ident == "std" && !has_path_arguments(&first_segment)
        {
            let option_module_segment = iter.next()?;
            if option_module_segment.ident == "option"
                || !has_path_arguments(&option_module_segment)
            {
                iter.next()?
            } else {
                return None;
            }
        } else if first_segment.ident == "Option" || has_path_arguments(&first_segment) {
            first_segment
        } else {
            return None;
        };

        let args = match option_segment.arguments {
            PathArguments::AngleBracketed(args) => args,
            _ => return None,
        };
        if args.colon2_token.is_some() {
            return None;
        }
        let mut args = args.args.into_iter();

        let ty = match args.next()? {
            GenericArgument::Type(ty) => ty,
            _ => return None,
        };
        if args.next().is_some() {
            return None;
        }
        let ty_path = match ty {
            Type::Path(path) => path,
            _ => return None,
        };
        if ty_path.qself.is_some() {
            println!("whoop");
            return None;
        }

        Some(ty_path.path.segments)
    })();

    if let Some(inner) = things_inside_option {
        (inner, true)
    } else {
        (original_segments, false)
    }
}

fn has_path_arguments(path_segment: &PathSegment) -> bool {
    match &path_segment.arguments {
        PathArguments::None => false,
        PathArguments::AngleBracketed(_) => true,
        PathArguments::Parenthesized(_) => true,
    }
}

impl Parse for AssociationType {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let ty = input.parse::<Type>()?;
        AssociationType::new(ty)
    }
}

#[cfg(test)]
mod test {
    #[allow(unused_imports)]
    use super::*;

    #[test]
    fn is_association_type_true() {
        let tokens = quote! { Association<'a, Country, CountryFactory> };
        let ty = syn::parse2::<AssociationType>(tokens).unwrap();

        assert_eq!(ty.lifetime.ident, "a");
        assert_eq!(ty.model_type, syn::parse2(quote! { Country }).unwrap());
        assert_eq!(
            ty.factory_type,
            syn::parse2(quote! { CountryFactory }).unwrap()
        );
        assert_eq!(ty.is_optional, false);
    }

    #[test]
    fn is_association_type_true_qualified() {
        let tokens = quote! { diesel_factories::Association<'b, Country, CountryFactory> };
        let ty = syn::parse2::<AssociationType>(tokens).unwrap();

        assert_eq!(ty.lifetime.ident, "b");
        assert_eq!(ty.model_type, syn::parse2(quote! { Country }).unwrap());
        assert_eq!(
            ty.factory_type,
            syn::parse2(quote! { CountryFactory }).unwrap()
        );
        assert_eq!(ty.is_optional, false);
    }

    #[test]
    fn is_association_type_true_optional() {
        let tokens = quote! { Option<Association<'a, Country, CountryFactory>> };
        let ty = syn::parse2::<AssociationType>(tokens).unwrap();

        assert_eq!(ty.lifetime.ident, "a");
        assert_eq!(ty.model_type, syn::parse2(quote! { Country }).unwrap());
        assert_eq!(
            ty.factory_type,
            syn::parse2(quote! { CountryFactory }).unwrap()
        );
        assert_eq!(ty.is_optional, true);
    }

    #[test]
    fn is_association_type_true_qualified_optional() {
        let tokens = quote! { Option<diesel_factories::Association<'b, Country, CountryFactory>> };
        let ty = syn::parse2::<AssociationType>(tokens).unwrap();

        assert_eq!(ty.lifetime.ident, "b");
        assert_eq!(ty.model_type, syn::parse2(quote! { Country }).unwrap());
        assert_eq!(
            ty.factory_type,
            syn::parse2(quote! { CountryFactory }).unwrap()
        );
        assert_eq!(ty.is_optional, true);
    }

    #[test]
    fn is_association_type_true_qualified_optional_qualified_option_also() {
        let tokens = quote! {
            std::option::Option<diesel_factories::Association<'b, Country, CountryFactory>>
        };
        let ty = syn::parse2::<AssociationType>(tokens).unwrap();

        assert_eq!(ty.lifetime.ident, "b");
        assert_eq!(ty.model_type, syn::parse2(quote! { Country }).unwrap());
        assert_eq!(
            ty.factory_type,
            syn::parse2(quote! { CountryFactory }).unwrap()
        );
        assert_eq!(ty.is_optional, true);
    }

    #[test]
    fn is_association_type_false() {
        let tokens = quote! { Country };
        let ty = syn::parse2::<AssociationType>(tokens);
        assert!(ty.is_err());
    }

    #[test]
    fn is_association_type_too_few_of_generic_args() {
        let tokens = quote! { Association<'a, Country> };
        let ty = syn::parse2::<AssociationType>(tokens);
        assert!(ty.is_err());
    }

    #[test]
    fn is_association_type_too_many_generic_args() {
        let tokens = quote! { Association<'a, Country, CountryFactory, i32> };
        let ty = syn::parse2::<AssociationType>(tokens);
        assert!(ty.is_err());
    }
}