aksr/
lib.rs

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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
//! # aksr
//!
//! `aksr` is a Rust derive macro designed to simplify struct management by automatically generating getter and setter methods for both named and tuple structs.
//!
//!
//! ## Example: Named Struct
//!
//! This example demonstrates the use of `aksr` with a named struct, `Rect`. The `attrs` field is set with an alias, a custom setter prefix, and the ability to increment values, while disabling the generation of a getter method for `attrs`.
//!
//! ```rust
//! use aksr::Builder;
//!
//! #[derive(Builder, Debug, Default)]
//! struct Rect {
//!     x: f32,
//!     y: f32,
//!     w: f32,
//!     h: f32,
//!     #[args(
//!         alias = "attributes",
//!         setter_prefix = "set",
//!         inc = true,
//!         getter = false
//!     )]
//!     attrs: Vec<String>,
//! }
//!
//! let rect = Rect::default()
//!     .with_x(0.0)
//!     .with_y(0.0)
//!     .with_w(10.0)
//!     .with_h(5.0)
//!     .set_attributes(&["A", "X", "Z"])
//!     .set_attributes_inc(&["O"])
//!     .set_attributes_inc(&["P"]);
//!
//! println!("rect: {:?}", rect);
//! println!("x: {}", rect.x());
//! println!("y: {}", rect.y());
//! println!("w: {}", rect.w());
//! println!("h: {}", rect.h());
//! println!("attrs: {:?}", rect.attrs);
//! // println!("attrs: {:?}", rect.attrs()); // Method `attrs` is not generated
//! ```
//!
//! ## Example: Tuple Struct
//!
//! Here, `aksr` is used with a tuple struct, `Color`. The example demonstrates customizing getter and setter prefixes, defining an alias for a specific field, and configuring one field to be incrementable.
//!
//! ```rust
//! use aksr::Builder;
//!
//! #[derive(Builder, Default, Debug)]
//! struct Color<'a>(
//!     u8,
//!     u8,
//!     u8,
//!     #[args(alias = "alpha")] f32,
//!     #[args(inc = true, getter_prefix = "get", setter_prefix = "set")] Vec<&'a str>,
//! );
//!
//! let color = Color::default()
//!     .with_0(255)
//!     .with_1(255)
//!     .with_2(0)
//!     .with_alpha(0.8)
//!     .set_4(&["A", "B", "C"])
//!     .set_4_inc(&["D", "E"]);
//!
//! println!(
//!     "RGBA: ({}, {}, {}, {}, {:?})",
//!     color.nth_0(),
//!     color.nth_1(),
//!     color.nth_2(),
//!     color.alpha(),
//!     color.get_4(),
//! );
//! ```
//!

use proc_macro::TokenStream;
use proc_macro2::{Ident, Span};
use quote::quote;
use syn::{
    parse_macro_input, Data, DataStruct, DeriveInput, Field, GenericArgument, Index, PathArguments,
    Type,
};

mod misc;
use misc::{Fns, Rules, Tys};

const ARGS: &str = "args";
const ALIAS: &str = "alias";
const GETTER: &str = "getter";
const SETTER: &str = "setter";
const SETTER_PREFIX: &str = "setter_prefix";
const GETTER_PREFIX: &str = "getter_prefix";
const INC_FOR_VEC: &str = "inc";
const SETTER_PREFIX_DEFAULT: &str = "with";
const GETTER_PREFIX_DEFAULT: &str = "nth";
const PRIMITIVE_TYPES: &[&str] = &[
    "i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128", "usize", "bool",
    "char", "unit", "f32", "f64",
];

#[proc_macro_derive(Builder, attributes(args))]
pub fn derive(x: TokenStream) -> TokenStream {
    let st = parse_macro_input!(x as DeriveInput);
    let expanded = build_expanded(st);
    TokenStream::from(expanded)
}

fn build_expanded(st: DeriveInput) -> proc_macro2::TokenStream {
    // generate code
    let code = match &st.data {
        Data::Struct(data) => generate_from_struct(data),
        Data::Enum(_) | Data::Union(_) => panic!("Builder(aksr) can only be derived for struct"),
    };

    // attrs
    let (struct_name, (impl_generics, ty_generics, where_clause)) =
        (&st.ident, &st.generics.split_for_impl());

    // token stream
    quote! {
        impl #impl_generics #struct_name #ty_generics #where_clause {
            #code
        }
    }
}

fn generate_from_struct(data_struct: &DataStruct) -> proc_macro2::TokenStream {
    // code container
    let mut codes = quote! {};

    // traverse
    for (idx, field) in data_struct.fields.iter().enumerate() {
        // build rules from field
        let rules = Rules::from(field);

        // generate code based on field
        match &field.ty {
            Type::Path(type_path) => {
                if let Some(last_segment) = type_path.path.segments.last() {
                    match last_segment.ident.to_string().as_str() {
                        "String" => {
                            generate(
                                field,
                                &rules,
                                idx,
                                None,
                                &mut codes,
                                Fns::Setter(Tys::String),
                            );
                            generate(
                                field,
                                &rules,
                                idx,
                                None,
                                &mut codes,
                                Fns::Getter(Tys::String),
                            );
                        }

                        "Vec" => {
                            // Vec<T> -> &[T]
                            if let PathArguments::AngleBracketed(args) = &last_segment.arguments {
                                if let Some(arg) = args.args.first() {
                                    if let GenericArgument::Type(ty) = arg {
                                        if let Type::Path(type_path) = &ty {
                                            if let Some(last_segment) =
                                                type_path.path.segments.last()
                                            {
                                                let ident = &last_segment.ident;

                                                // Vec<String> -> &[&str]
                                                if ident == "String" {
                                                    generate(
                                                        field,
                                                        &rules,
                                                        idx,
                                                        None,
                                                        &mut codes,
                                                        Fns::Setter(Tys::VecString),
                                                    );

                                                    // increment ver
                                                    generate(
                                                        field,
                                                        &rules,
                                                        idx,
                                                        None,
                                                        &mut codes,
                                                        Fns::Setter(Tys::VecStringInc),
                                                    );
                                                } else {
                                                    // setters
                                                    generate(
                                                        field,
                                                        &rules,
                                                        idx,
                                                        Some(arg),
                                                        &mut codes,
                                                        Fns::Setter(Tys::Vec),
                                                    );

                                                    // setters inc
                                                    generate(
                                                        field,
                                                        &rules,
                                                        idx,
                                                        Some(arg),
                                                        &mut codes,
                                                        Fns::Setter(Tys::VecInc),
                                                    );
                                                }

                                                // getters: Vec<T> -> &[T]
                                                generate(
                                                    field,
                                                    &rules,
                                                    idx,
                                                    Some(arg),
                                                    &mut codes,
                                                    Fns::Getter(Tys::Vec),
                                                );
                                            }
                                        } else {
                                            // Vec<T> -> &[T]
                                            // setters
                                            generate(
                                                field,
                                                &rules,
                                                idx,
                                                Some(arg),
                                                &mut codes,
                                                Fns::Setter(Tys::Vec),
                                            );

                                            // setters inc
                                            generate(
                                                field,
                                                &rules,
                                                idx,
                                                Some(arg),
                                                &mut codes,
                                                Fns::Setter(Tys::VecInc),
                                            );
                                            // getters: Vec<T> -> &[T]
                                            generate(
                                                field,
                                                &rules,
                                                idx,
                                                Some(arg),
                                                &mut codes,
                                                Fns::Getter(Tys::Vec),
                                            );
                                        }
                                    }
                                }
                            }
                        }

                        "Option" => {
                            // Option<T>
                            // - T => String => &str
                            // - T => Vec<U> => &[U]
                            //   - U => String => &str
                            if let PathArguments::AngleBracketed(args) = &last_segment.arguments {
                                if let Some(arg) = &args.args.first() {
                                    if let GenericArgument::Type(ty) = arg {
                                        if let Type::Path(type_path) = &ty {
                                            if let Some(last_segment) =
                                                type_path.path.segments.last()
                                            {
                                                let ident = &last_segment.ident;
                                                // T => Vec<U> => &[U]
                                                if ident == "Vec" {
                                                    if let PathArguments::AngleBracketed(args) =
                                                        &last_segment.arguments
                                                    {
                                                        // U
                                                        if let Some(arg) = args.args.first() {
                                                            if let GenericArgument::Type(
                                                                Type::Path(type_path),
                                                            ) = arg
                                                            {
                                                                if let Some(last_segment) =
                                                                    type_path.path.segments.last()
                                                                {
                                                                    // U => String => &str
                                                                    // Option<Vec<String>> -> Option<&[&str]>
                                                                    if last_segment.ident
                                                                        == "String"
                                                                    {
                                                                        generate(
                                                                            field,
                                                                            &rules,
                                                                            idx,
                                                                            None,
                                                                            &mut codes,
                                                                            Fns::Setter(Tys::OptionVecString),
                                                                        );
                                                                    } else {
                                                                        generate(
                                                                            field,
                                                                            &rules,
                                                                            idx,
                                                                            Some(arg),
                                                                            &mut codes,
                                                                            Fns::Setter(
                                                                                Tys::OptionVec,
                                                                            ),
                                                                        );
                                                                    }
                                                                }
                                                            } else {
                                                                generate(
                                                                    field,
                                                                    &rules,
                                                                    idx,
                                                                    Some(arg),
                                                                    &mut codes,
                                                                    Fns::Setter(Tys::OptionVec),
                                                                );
                                                            }

                                                            // getters: Option<Vec<T>> -> Option<&[T]>
                                                            generate(
                                                                field,
                                                                &rules,
                                                                idx,
                                                                Some(arg),
                                                                &mut codes,
                                                                Fns::Getter(Tys::OptionVec),
                                                            );
                                                        }
                                                    }
                                                } else if ident == "String" {
                                                    // T => String => &str
                                                    generate(
                                                        field,
                                                        &rules,
                                                        idx,
                                                        Some(arg),
                                                        &mut codes,
                                                        Fns::Setter(Tys::OptionString),
                                                    );

                                                    // getters: Option<String> -> Option<&str>
                                                    generate(
                                                        field,
                                                        &rules,
                                                        idx,
                                                        Some(arg),
                                                        &mut codes,
                                                        Fns::Getter(Tys::OptionString),
                                                    );
                                                } else {
                                                    // T => T
                                                    generate(
                                                        field,
                                                        &rules,
                                                        idx,
                                                        Some(arg),
                                                        &mut codes,
                                                        Fns::Setter(Tys::Option),
                                                    );

                                                    if PRIMITIVE_TYPES
                                                        .contains(&ident.to_string().as_str())
                                                    {
                                                        // getters: Option<T> -> Option<T>
                                                        generate(
                                                            field,
                                                            &rules,
                                                            idx,
                                                            Some(arg),
                                                            &mut codes,
                                                            Fns::Getter(Tys::Option),
                                                        );
                                                    } else {
                                                        // getters: Option<T> -> Option<&T>
                                                        // Option<Box<T>>, Option<Option<T>>
                                                        generate(
                                                            field,
                                                            &rules,
                                                            idx,
                                                            Some(arg),
                                                            &mut codes,
                                                            Fns::Getter(Tys::OptionAsRef),
                                                        );
                                                    }
                                                }
                                            }
                                        } else {
                                            //  others: Option<(u8, i8)>, Option<&'a str>,
                                            if let PathArguments::AngleBracketed(args) =
                                                &last_segment.arguments
                                            {
                                                if let Some(arg) = args.args.first() {
                                                    // setters
                                                    generate(
                                                        field,
                                                        &rules,
                                                        idx,
                                                        Some(arg),
                                                        &mut codes,
                                                        Fns::Setter(Tys::Option),
                                                    );

                                                    // getters
                                                    if let GenericArgument::Type(ty) = arg {
                                                        match ty {
                                                            Type::Reference(_) => {
                                                                // getters: Option<T> -> Option<T>
                                                                // Option<&'a str>
                                                                generate(
                                                                    field,
                                                                    &rules,
                                                                    idx,
                                                                    Some(arg),
                                                                    &mut codes,
                                                                    Fns::Getter(Tys::Option),
                                                                );
                                                            }
                                                            _ => {
                                                                // getters: Option<T> -> Option<&T>
                                                                // Option<(u8, i8)>
                                                                generate(
                                                                    field,
                                                                    &rules,
                                                                    idx,
                                                                    Some(arg),
                                                                    &mut codes,
                                                                    Fns::Getter(Tys::OptionAsRef),
                                                                );
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        xxx => {
                            generate(
                                field,
                                &rules,
                                idx,
                                None,
                                &mut codes,
                                Fns::Setter(Tys::Basic),
                            );
                            if PRIMITIVE_TYPES.contains(&xxx) {
                                generate(
                                    field,
                                    &rules,
                                    idx,
                                    None,
                                    &mut codes,
                                    Fns::Getter(Tys::Basic),
                                );
                            } else {
                                generate(
                                    field,
                                    &rules,
                                    idx,
                                    None,
                                    &mut codes,
                                    Fns::Getter(Tys::Ref),
                                );
                            }
                        }
                    }
                }
            }
            ty => {
                // setter
                generate(
                    field,
                    &rules,
                    idx,
                    None,
                    &mut codes,
                    Fns::Setter(Tys::Basic),
                );

                // getter
                match ty {
                    Type::Reference(_) => {
                        // &'a T or &'a mut T
                        generate(
                            field,
                            &rules,
                            idx,
                            None,
                            &mut codes,
                            Fns::Getter(Tys::Basic),
                        );
                    }
                    Type::Array(_) | Type::Tuple(_) => {
                        // array [T; n] and tuple (A, B, C, String)
                        generate(field, &rules, idx, None, &mut codes, Fns::Getter(Tys::Ref));
                    }
                    _ => {
                        // TODO: others
                        generate(field, &rules, idx, None, &mut codes, Fns::Getter(Tys::Ref));
                    }
                }
            }
        }
    }

    // token stream
    quote! {
        #codes
    }
}

fn generate(
    field: &Field,
    rules: &Rules,
    idx: usize,
    arg: Option<&GenericArgument>,
    codes: &mut proc_macro2::TokenStream,
    fn_type: Fns,
) {
    // setter_name & getter_name
    let (setter_name, getter_name) = rules.generate_setter_getter_names(field, idx); // (move inside????)

    // attrs
    let field_type = &field.ty;
    let field_name = field.ident.as_ref();
    let field_index = Index::from(idx);
    let field_access = field_name.map_or_else(|| quote! { #field_index }, |name| quote! { #name });

    // token stream
    let code = match fn_type {
        Fns::Setter(ty) => {
            if !rules.gen_setter {
                return;
            }
            match ty {
                Tys::Basic => {
                    quote! {
                        pub fn #setter_name(mut self, x: #field_type) -> Self {
                            self.#field_access = x;
                            self
                        }
                    }
                }
                Tys::String => {
                    quote! {
                        pub fn #setter_name(mut self, x: &str) -> Self {
                            self.#field_access = x.to_string();
                            self
                        }
                    }
                }
                Tys::Vec => {
                    let arg = arg.expect("Vec setter requires a generic argument");
                    quote! {
                        pub fn #setter_name(mut self, x: &[#arg]) -> Self {
                            self.#field_access = x.to_vec();
                            self
                        }
                    }
                }
                Tys::VecInc if rules.inc_for_vec => {
                    let arg = arg.expect("VecInc setter requires a generic argument");
                    let setter_name = Ident::new(
                        &format!("{}_{}", setter_name, INC_FOR_VEC),
                        Span::call_site(),
                    );
                    quote! {
                        pub fn #setter_name(mut self, x: &[#arg]) -> Self {
                            if self.#field_access.is_empty() {
                                self.#field_access = Vec::from(x);
                            } else {
                                self.#field_access.extend_from_slice(x);
                            }
                            self
                        }
                    }
                }
                Tys::VecString => {
                    quote! {
                        pub fn #setter_name(mut self, x: &[&str]) -> Self {
                            self.#field_access = x.iter().map(|s| s.to_string()).collect();
                            self
                        }
                    }
                }
                Tys::VecStringInc if rules.inc_for_vec => {
                    let setter_name = Ident::new(
                        &format!("{}_{}", setter_name, INC_FOR_VEC),
                        Span::call_site(),
                    );
                    quote! {
                        pub fn #setter_name(mut self, x: &[&str]) -> Self {
                            if self.#field_access.is_empty() {
                                self.#field_access = x.iter().map(|s| s.to_string()).collect();
                            } else {
                                let mut x = x.iter().map(|s| s.to_string()).collect::<Vec<_>>();
                                self.#field_access.append(&mut x);
                            }
                            self
                        }
                    }
                }
                Tys::Option => {
                    quote! {
                        pub fn #setter_name(mut self, x: #arg) -> Self {
                            self.#field_access = Some(x);
                            self
                        }
                    }
                }
                Tys::OptionVec => {
                    let arg = arg.expect("OptionVec setter requires a generic argument");
                    quote! {
                        pub fn #setter_name(mut self, x: &[#arg]) -> Self {
                            self.#field_access = Some(x.to_vec());
                            self
                        }
                    }
                }
                Tys::OptionVecString => {
                    quote! {
                        pub fn #setter_name(mut self, x: &[&str]) -> Self {
                            self.#field_access = Some(x.iter().map(|s| s.to_string()).collect());
                            self
                        }
                    }
                }
                Tys::OptionString => {
                    quote! {
                        pub fn #setter_name(mut self, x: &str) -> Self {
                            self.#field_access = Some(x.to_string());
                            self
                        }
                    }
                }
                _ => quote! {},
            }
        }
        Fns::Getter(ty) => {
            if !rules.gen_getter {
                return;
            }
            match ty {
                Tys::Basic => {
                    quote! {
                        pub fn #getter_name(&self) -> #field_type {
                            self.#field_access
                        }
                    }
                }
                Tys::Ref => {
                    quote! {
                        pub fn #getter_name(&self) -> &#field_type {
                            &self.#field_access
                        }
                    }
                }
                Tys::String => {
                    quote! {
                        pub fn #getter_name(&self) -> &str {
                            &self.#field_access
                        }
                    }
                }
                Tys::Vec => {
                    let arg = arg.expect("Vec getter requires a generic argument");
                    quote! {
                        pub fn #getter_name(&self) -> &[#arg] {
                            &self.#field_access
                        }
                    }
                }
                Tys::Option => {
                    let arg = arg.expect("Option getter requires a generic argument");
                    quote! {
                        pub fn #getter_name(&self) -> Option<#arg> {
                            self.#field_access
                        }
                    }
                }
                Tys::OptionAsRef => {
                    let arg = arg.expect("OptionAsRef getter requires a generic argument");
                    quote! {
                        pub fn #getter_name(&self) -> Option<&#arg> {
                            self.#field_access.as_ref()
                        }
                    }
                }
                Tys::OptionString => {
                    quote! {
                        pub fn #getter_name(&self) -> Option<&str> {
                            self.#field_access.as_deref()
                        }
                    }
                }
                Tys::OptionVec => {
                    let arg = arg.expect("OptionVec getter requires a generic argument");
                    quote! {
                        pub fn #getter_name(&self) -> Option<&[#arg]> {
                            self.#field_access.as_deref()
                        }
                    }
                }
                _ => quote! {},
            }
        }
    };

    // append
    codes.extend(code);
}