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
//! This crate provides attribute based convenience method generation (accessor/updater/mutator/constructor) for structs with private fields.
//!
//! The observed results achieved by the crate's attibute macros are somewhat similar to that of the `@Getter`/`@Setter` and the `@RequiredArgsConstructor`/`@AllArgsConstructor` annotations of __Java__ library [Lombok], with a __Rust__ flavor.
//!
//! [Lombok]: https://projectlombok.org/
//!
//! # Example
//!
//! ```
//! mod examples {
//!     use purpurea::*;
//!     
//!     #[accessors(email)]
//!     #[updaters(email)]
//!     #[default_constructor]
//!     pub struct User {
//!         email: String,
//!         account_number: usize
//!     }
//! }
//!     
//! use examples::*;
//!
//! let john_doe = User::new("john_doe@example.com", 45275);
//! let new_email = "john_doe@example2.com";
//! let john_doe2 = john_doe.with_email(new_email.to_owned());
//!
//! assert_eq!(new_email, john_doe2.email());
//! ```

extern crate proc_macro;

use proc_macro::{TokenStream, TokenTree};
use quote::*;
use std::collections::HashSet;
use syn::*;

/// Generates accessor methods with names corresponding to those of the the struct's fields.
///
///  Accessors take `&self` and return a reference to the corresponding field. You can use the [macro@accessors] attribute with or without providing field names.
///
/// For [Copy] types, you will need to apply dereferencing in order to obtain the value. This is a price for keeping things simple.
///
/// # Examples
///
/// If you don't provide a list of field names, accessors to all fields are going to be generated by the attribute macro.
/// ```
/// mod examples {
///     use purpurea::*;
///
///     #[accessors]
///     pub struct Address {
///         city: String,
///         street: String,
///         number: u16,
///         verified: bool
///     }
///
///     impl Address {
///         pub fn new(city: &str, street: &str, number: u16) -> Self {
///             Self {
///                 city: city.to_owned(),
///                 street: street.to_owned(),
///                 number,
///                 verified: false
///             }
///         }
///     }
/// }
///
/// use examples::*;
///
/// let city: &str = "Los Angeles";
/// let street: &str = "Elm street";
/// let number: u16 = 13;
///
/// let new_address = Address::new(city, street, number);
///
/// assert_eq!(city, new_address.city());
/// assert_eq!(street, new_address.street());
/// assert_eq!(number, *new_address.number());
/// assert!(!*new_address.verified());
/// ```
/// You can control which fields should have accessors by providing the list of field names (comma-separated if multiple).
/// ```
/// mod examples {
///     use purpurea::*;
///     
///     #[accessors(email, is_admin)]
///     pub struct User {
///         email: String,
///         account_number: usize,
///         is_admin: bool
///     }
///
///     impl User {
///         pub fn new(email: &str, account_number: usize, is_admin: bool) -> Self {
///             Self {
///                 email: email.to_owned(),
///                 account_number,
///                 is_admin
///             }
///         }
///     }
///     
/// }
///
/// use examples::*;
///
/// let email = "john_doe@example.com";
/// let john_doe = User::new(email, 45275, true);
///
/// assert_eq!(email, john_doe.email());
/// assert!(*john_doe.is_admin());
/// ```
///
/// # Panics
///
/// Panics if it's applied on tuple structs, enums (and their struct variants), or structs with generics (including lifetime parameters).
///
#[proc_macro_attribute]
pub fn accessors(attr: TokenStream, item: TokenStream) -> TokenStream {
    accessors_impl(
        check_generics(parse_macro_input![item as ItemStruct]),
        extract_fields_from_attributes(&attr),
    )
}

/// Generates updater methods with names corresponding to those of the the struct's fields, with a prefix of `with_`. You won't have to declare your values mutable.
///
/// Updaters take `self` and a new value with the type of the corresponding field as arguments, and return `Self` so they can be chained.
///
/// You can use the [macro@updaters] attribute with or without providing field names.
///
/// # Examples
///
/// If you don't provide a list of field names, updaters to all fields are going to be generated by the attribute macro.
/// ```
/// mod examples {
///     use purpurea::*;
///
///     #[updaters]
///     #[derive(Debug, Eq, PartialEq)]
///     pub struct Address {
///         city: String,
///         street: String,
///         number: u16,
///         verified: bool
///     }
///
///     impl Address {
///         pub fn new(city: &str, street: &str, number: u16) -> Self {
///             Self {
///                 city: city.to_owned(),
///                 street: street.to_owned(),
///                 number,
///                 verified: false
///             }
///         }
///     }
/// }
///
/// use examples::*;
///
/// let new_york = "New York";
/// let street = "Elm street";
/// let sixty_six = 66;
///
/// let new_address = Address::new("Los Angeles", street, 13);
/// let new_address_updated = new_address
///     .with_city(new_york.to_owned())
///     .with_number(sixty_six);
///
/// assert_eq!(Address::new(new_york, street, sixty_six), new_address_updated);
/// ```
/// You can control which fields should have updaters by providing the list of field names (comma-separated if multiple).
/// ```
/// mod examples {
///     use purpurea::*;
///     
///     #[updaters(email, is_admin)]
///     #[derive(Debug, Eq, PartialEq)]
///     pub struct User {
///         email: String,
///         account_number: usize,
///         is_admin: bool
///     }
///
///     impl User {
///         pub fn new(email: &str, account_number: usize, is_admin: bool) -> Self {
///             Self {
///                 email: email.to_owned(),
///                 account_number,
///                 is_admin
///             }
///         }
///     }
///     
/// }
/// use examples::*;
///
/// let acct = 45275;
/// let john_doe = User::new("john_doe@example.com", acct, false);
/// let new_email = "john_doe@example2.com";
/// let john_doe2 = john_doe
///     .with_email(new_email.to_owned())
///     .with_is_admin(true);
///
/// assert_eq!(User::new(new_email, acct, true), john_doe2);
/// ```
///
/// # Panics
///
/// Panics if it's applied on tuple structs, enums (and their struct variants), or structs with generics (including lifetime parameters).
///
#[proc_macro_attribute]
pub fn updaters(attr: TokenStream, item: TokenStream) -> TokenStream {
    updaters_impl(
        check_generics(parse_macro_input![item as ItemStruct]),
        extract_fields_from_attributes(&attr),
    )
}

/// Generates mutator methods with names corresponding to those of the the struct's fields, with a prefix of `set_`.
///
/// Mutators take `&mut self` and a new value with the type of the corresponding field as arguments, and return `&mut Self` so they can be chained.
///
/// You can use the [macro@mutators] attribute with or without providing field names.
///
/// # Examples
///
/// If you don't provide a list of field names, mutators to all fields are going to be generated by the attribute macro.
/// ```
/// mod examples {
///     use purpurea::*;
///
///     #[mutators]
///     #[derive(Debug, Eq, PartialEq)]
///     pub struct Address {
///         city: String,
///         street: String,
///         number: u16,
///         verified: bool
///     }
///
///     impl Address {
///         pub fn new(city: &str, street: &str, number: u16) -> Self {
///             Self {
///                 city: city.to_owned(),
///                 street: street.to_owned(),
///                 number,
///                 verified: false
///             }
///         }
///     }
/// }
///
/// use examples::*;
///
/// let new_york = "New York";
/// let street = "Elm street";
/// let sixty_six = 66;
///
/// let mut new_address = Address::new("Los Angeles", street, 13);
/// new_address
///     .set_city(new_york.to_owned())
///     .set_number(sixty_six);
///
/// assert_eq!(Address::new(new_york, street, sixty_six), new_address);
/// ```
/// You can control which fields should have mutators by providing the list of field names (comma-separated if multiple).
/// ```
/// mod examples {
///     use purpurea::*;
///     
///     #[mutators(email, is_admin)]
///     #[derive(Debug, Eq, PartialEq)]
///     pub struct User {
///         email: String,
///         account_number: usize,
///         is_admin: bool
///     }
///
///     impl User {
///         pub fn new(email: &str, account_number: usize, is_admin: bool) -> Self {
///             Self {
///                 email: email.to_owned(),
///                 account_number,
///                 is_admin
///             }
///         }
///     }
///     
/// }
/// use examples::*;
///
/// let acct = 45275;
/// let mut john_doe = User::new("john_doe@example.com", acct, false);
/// let new_email = "john_doe@example2.com";
/// john_doe
///     .set_email(new_email.to_owned())
///     .set_is_admin(true);
///
/// assert_eq!(User::new(new_email, acct, true), john_doe);
/// ```
///
/// # Panics
///
/// Panics if it's applied on tuple structs, enums (and their struct variants), or structs with generics (including lifetime parameters).
///
#[proc_macro_attribute]
pub fn mutators(attr: TokenStream, item: TokenStream) -> TokenStream {
    mutators_impl(
        check_generics(parse_macro_input![item as ItemStruct]),
        extract_fields_from_attributes(&attr),
    )
}

/// Generates a constructor method called `new`.
///
/// For field types `T`, the corresponding constructor argument type will be `T`. For `String` fields, the argument type will be `&str`.
///
/// The order of arguments will be the same as in the definition of the struct.
///
/// You can use the [macro@default_constructor] attribute with or without providing field names.
///
/// # Examples
///
/// If you don't provide a list of field names, the constructor will require the values for all fields as arguments.
/// ```
/// use purpurea::*;
///   
/// #[default_constructor]
/// #[derive(Debug, Eq, PartialEq)]
/// pub struct User {
///     email: String,
///     account_number: usize,
///     bonus_points: Option<u64>
/// }
///
/// let email = "john_doe@example.com";
/// let account_number = 45275;
/// let bonus_points = None;
/// let john_doe = User::new(email, account_number, bonus_points);
/// let john_doe2 = User { email: email.to_owned(), account_number, bonus_points };
///
/// assert_eq!(john_doe, john_doe2);
/// ```
/// You can control the arguments the constructor should take by providing the list of field names (comma-separated if multiple).
///
/// Fields omitted are going to use the default value of the corresponding type, provided by the [Default] trait. If the type does not implement [Default], the macro will fail.
/// ```
/// use purpurea::*;    
///
/// #[default_constructor(city, street, number)]
/// #[derive(Debug, Eq, PartialEq)]
/// pub struct Address {
///     city: String,
///     street: String,
///     number: u16,
///     verified: bool,
///     coordinates: Option<Vec<u16>>
/// }
///
/// let city = "Los Angeles";
/// let street = "Elm street";
/// let number = 13;
/// let verified = false;
/// let new_address = Address::new(city, street, number);
/// let new_address2 =
///     Address {
///         city: city.to_owned(),
///         street: street.to_owned(),
///         number,
///         verified,
///         coordinates: None
///     };
///
/// assert_eq!(new_address, new_address2);
/// ```
///
/// # Panics
///
/// Panics if it's applied on tuple structs, enums (and their struct variants), or structs with generics (including lifetime parameters).
/// 
/// Also panics when a field's type should implement [Default] but it doesn't.
///
#[proc_macro_attribute]
pub fn default_constructor(attr: TokenStream, item: TokenStream) -> TokenStream {
    default_constructor_impl(
        check_generics(parse_macro_input![item as ItemStruct]),
        extract_fields_from_attributes(&attr),
    )
}

fn accessors_impl(struct_definition: ItemStruct, fields: HashSet<String>) -> TokenStream {
    generate_access_update_mutate(struct_definition, fields, Task::Access)
}

fn updaters_impl(struct_definition: ItemStruct, fields: HashSet<String>) -> TokenStream {
    generate_access_update_mutate(struct_definition, fields, Task::Update)
}

fn mutators_impl(struct_definition: ItemStruct, fields: HashSet<String>) -> TokenStream {
    generate_access_update_mutate(struct_definition, fields, Task::Mutate)
}

fn default_constructor_impl(struct_definition: ItemStruct, fields: HashSet<String>) -> TokenStream {
    let struct_name = &struct_definition.ident;
    let trait_name = format_ident!("{}DefaultConstructor", struct_name);
    let determine_type_and_applied =
        |ty: &Type, id: &Ident| match ty.to_token_stream().to_string().as_ref() {
            "String" => (quote![&str], quote![#id.to_owned()]),
            _ => {
                if fields.is_empty() || fields.contains(&id.to_string()) {
                    (quote![#ty], quote![#id])
                } else {
                    (quote![#ty], quote![<#ty as Default>::default()])
                }
            }
        };

    let mut args = vec![];
    let mut applied = vec![];

    struct_definition
        .fields
        .iter()
        .for_each(|field| match &field.ident {
            Some(id) => {
                let (ty, rhs) = determine_type_and_applied(&field.ty, id);
                if fields.is_empty() || fields.contains(&id.to_string()) {
                    args.push(quote![#id: #ty,]);
                }
                applied.push(quote![#id: #rhs,]);
            }
            _ => panic!["Constructor generation is not supported for unnamed fields!"],
        });

    quote![
        #struct_definition

        pub trait #trait_name {
            fn new(#(#args)*) -> Self;
        }

        impl #trait_name for #struct_name {
            fn new(#(#args)*) -> Self {
                Self { #(#applied)* }
            }
        }
    ]
    .into()
}

enum Task {
    Access,
    Update,
    Mutate,
}

fn generate_access_update_mutate(
    struct_definition: ItemStruct,
    fields: HashSet<String>,
    task: Task,
) -> TokenStream {
    let struct_name = &struct_definition.ident;
    let trait_name = match task {
        Task::Access => format_ident!("{}Accessors", struct_name),
        Task::Update => format_ident!("{}Updaters", struct_name),
        Task::Mutate => format_ident!("{}Mutators", struct_name),
    };
    let determine_return_type = |ty: &Type| match ty.to_token_stream().to_string().as_ref() {
        "String" => quote![&str],
        _ => quote![&#ty],
    };

    let mut definitions = vec![];
    let mut impls = vec![];

    struct_definition
        .fields
        .iter()
        .filter(|field| {
            if fields.is_empty() {
                true
            } else {
                match &field.ident {
                    Some(id) => fields.contains(&id.to_string()),
                    _ => false,
                }
            }
        })
        .for_each(|field| match &field.ident {
            Some(id) => match task {
                Task::Access => {
                    let ty = determine_return_type(&field.ty);
                    definitions.push(quote![fn #id(&self) -> #ty;]);
                    impls.push(quote![
                        fn #id(&self) -> #ty {
                            &self.#id
                        }
                    ]);
                }
                Task::Update => {
                    let ty = &field.ty;
                    let fn_name = format_ident!("with_{}", id);
                    definitions.push(quote![fn #fn_name(self, new_value: #ty) -> Self;]);
                    impls.push(quote![
                        fn #fn_name(self, new_value: #ty) -> Self {
                            let mut temp = self;
                            temp.#id = new_value;
                            temp
                        }
                    ]);
                }
                Task::Mutate => {
                    let ty = &field.ty;
                    let fn_name = format_ident!("set_{}", id);
                    definitions.push(quote![fn #fn_name(&mut self, new_value: #ty) -> &mut Self;]);
                    impls.push(quote![
                        fn #fn_name(&mut self, new_value: #ty) -> &mut Self {
                            self.#id = new_value;
                            self
                        }
                    ]);
                }
            },
            _ => panic!["Accessor/Updater/Mutator generation is not supported for unnamed fields!"],
        });

    quote![
        #struct_definition

        pub trait #trait_name {
            #(#definitions)*
        }

        impl #trait_name for #struct_name {
            #(#impls)*
        }
    ]
    .into()
}

fn extract_fields_from_attributes(attributes: &TokenStream) -> HashSet<String> {
    attributes
        .clone()
        .into_iter()
        .flat_map(|token| match token {
            TokenTree::Ident(ident) => Some(ident.to_string()),
            _ => None,
        })
        .collect()
}

fn check_generics(struct_definition: ItemStruct) -> ItemStruct {
    if !struct_definition.generics.params.is_empty() {
        panic!["Structs with generics are currently unsupported."];
    } else {
        struct_definition
    }
}