enum_companion_derive 0.1.4

A procedural macro for generating companion enums for structs.
Documentation
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
//! # Enum Companion Derive
//!
//! This crate provides the procedural macro for `enum_companion`.
//!
//! Please refer to the [enum_companion](https://docs.rs/enum_companion) documentation for detailed usage and examples.

use darling::{FromDeriveInput, FromField, ast::Data, util::PathList};
use proc_macro::TokenStream;
use quote::quote;
use syn::{
    DeriveInput, Ident, Type,
    ext::IdentExt,
    parse_macro_input,
    visit::{self, Visit},
};

/// Attributes that can be applied to fields of the struct.
#[derive(FromField, Clone)]
#[darling(attributes(companion))]
struct FieldAttrs {
    ident: Option<Ident>,
    ty: Type,
    /// Rename the enum variant for this field.
    rename: Option<String>,
    /// The title of the field, used for display or documentation purposes.
    #[darling(default)]
    title: Option<String>,
    /// The description of the field, used for documentation purposes.
    #[darling(default)]
    description: Option<String>,
    /// The order of the field, used for sorting or display purposes.
    #[darling(default)]
    order: Option<isize>,
    /// Skip this field from being included in the companion enums.
    #[darling(default)]
    skip: bool,
}

/// Options for the `EnumCompanion` derive macro.
#[derive(FromDeriveInput)]
#[darling(attributes(companion), supports(struct_named))]
struct CompanionOpts {
    ident: Ident,
    vis: syn::Visibility,
    generics: syn::Generics,
    data: Data<(), FieldAttrs>,
    /// The name of the function to get a value from the struct.
    #[darling(default = "default_value_fn")]
    value_fn: String,
    /// The name of the function to update a value in the struct.
    #[darling(default = "default_update_fn")]
    update_fn: String,
    /// The name of the function to get a list of all fields.
    #[darling(default = "default_fields_fn")]
    fields_fn: String,
    /// A list of traits to derive for the field enum.
    #[darling(default)]
    derive_field: PathList,
    /// A list of traits to derive for the value enum.
    #[darling(default)]
    derive_value: PathList,
    /// Serde attributes for the field enum.
    #[darling(default)]
    serde_field: Option<syn::Meta>,
    /// Serde attributes for the value enum.
    #[darling(default)]
    serde_value: Option<syn::Meta>,
}

/// Default name for the `value` function.
fn default_value_fn() -> String {
    "value".to_string()
}

/// Default name for the `update` function.
fn default_update_fn() -> String {
    "update".to_string()
}

/// Default name for the `fields` function.
fn default_fields_fn() -> String {
    "fields".to_string()
}

#[proc_macro_derive(EnumCompanion, attributes(companion))]
pub fn enum_companion_derive(input: TokenStream) -> TokenStream {
    // Parse the input tokens into a syntax tree.
    let input = parse_macro_input!(input as DeriveInput);
    // Parse the macro options from the derive input.
    let opts = match CompanionOpts::from_derive_input(&input) {
        Ok(val) => val,
        Err(err) => {
            return err.write_errors().into();
        }
    };

    // Get the struct's name, visibility, and other options.
    let struct_name = opts.ident;
    let vis = opts.vis;
    let generics = opts.generics;
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
    let value_fn_name = Ident::new(&opts.value_fn, struct_name.span());
    let update_fn_name = Ident::new(&opts.update_fn, struct_name.span());
    let fields_fn_name = Ident::new(&opts.fields_fn, struct_name.span());
    let derive_field = opts.derive_field;
    let derive_value = opts.derive_value;
    let serde_field = &opts.serde_field;
    let serde_field_attr = if let Some(syn::Meta::List(serde_field)) = serde_field {
        // Convert the serde attributes to a token stream.
        let attr_tokens: proc_macro2::TokenStream = serde_field.tokens.clone();
        quote! { #[serde(#attr_tokens)] }
    } else {
        quote! {}
    };
    let serde_value = &opts.serde_value;
    let serde_value_attr = if let Some(syn::Meta::List(serde_value)) = serde_value {
        let attr_tokens: proc_macro2::TokenStream = serde_value.tokens.clone();
        quote! { #[serde(#attr_tokens)] }
    } else {
        quote! {}
    };

    // Get the struct's fields.
    let fields = opts.data.take_struct().unwrap();

    let mut field_idents = Vec::new();
    let mut field_types = Vec::new();
    let mut field_variants = Vec::new();
    let mut from_str_arms = Vec::new();
    let mut field_attrs_vec = Vec::new();

    // Iterate over the fields and extract the necessary information.
    for field in fields.fields {
        if field.skip {
            continue;
        }

        let ident = field.ident.clone().unwrap();
        let ident_unraw = ident.unraw().to_string();
        let variant_name_str = field
            .rename
            .clone()
            .unwrap_or_else(|| to_pascal_case(&ident_unraw));
        let variant = Ident::new(&variant_name_str, ident.span());

        let ident_str = ident_unraw.clone();
        let mut patterns = vec![ident_str.clone()];
        if variant_name_str != ident_str {
            patterns.push(variant_name_str);
        }

        from_str_arms.push(quote! {
            #(#patterns)|* => Ok(Self::#variant)
        });

        field_idents.push(ident);
        field_types.push(field.ty.clone());
        field_variants.push(variant);
        field_attrs_vec.push(field);
    }

    // Create the names for the generated enums.
    let field_enum_name = syn::Ident::new(&format!("{struct_name}Field"), struct_name.span());
    let value_enum_name = syn::Ident::new(&format!("{struct_name}Value"), struct_name.span());

    // Prepare the variants for the field enum.
    let field_enum_variants = field_variants.iter();
    let _field_variants_count = field_variants.len();

    // Prepare the variants for the value enum.
    let value_enum_variants = field_variants
        .iter()
        .zip(field_types.iter())
        .map(|(variant, ty)| {
            quote! { #variant(#ty) }
        });

    // Prepare the match arms for the `value` function.
    let value_match_arms =
        field_idents
            .iter()
            .zip(field_variants.iter())
            .map(|(ident, variant)| {
                quote! {
                    #field_enum_name::#variant => #value_enum_name::#variant(self.#ident.clone())
                }
            });

    // Prepare the match arms for the `update` function.
    let update_match_arms =
        field_idents
            .iter()
            .zip(field_variants.iter())
            .map(|(ident, variant)| {
                quote! {
                    #value_enum_name::#variant(value) => self.#ident = value
                }
            });

    let enum_companion_field_impl = {
        let name_arms =
            field_variants
                .iter()
                .zip(field_attrs_vec.iter())
                .map(|(variant, attrs)| {
                    let name = attrs
                        .rename
                        .clone()
                        .unwrap_or_else(|| attrs.ident.as_ref().unwrap().unraw().to_string());
                    quote! { Self::#variant => #name }
                });

        let type_str_arms = field_variants
            .iter()
            .zip(field_types.iter())
            .map(|(variant, ty)| {
                let type_str = quote!(#ty).to_string();
                quote! { Self::#variant => #type_str }
            });

        let title_arms =
            field_variants
                .iter()
                .zip(field_attrs_vec.iter())
                .map(|(variant, attrs)| {
                    let title = attrs.title.as_ref().map(|t| quote!(#t)).unwrap_or_else(|| {
                        let name = attrs
                            .rename
                            .clone()
                            .unwrap_or_else(|| attrs.ident.as_ref().unwrap().unraw().to_string());
                        quote!(#name)
                    });
                    quote! { Self::#variant => #title }
                });

        let description_arms =
            field_variants
                .iter()
                .zip(field_attrs_vec.iter())
                .map(|(variant, attrs)| {
                    let description = attrs
                        .description
                        .as_ref()
                        .map(|d| quote!(#d))
                        .unwrap_or_else(|| quote!(""));
                    quote! { Self::#variant => #description }
                });

        let order_arms =
            field_variants
                .iter()
                .zip(field_attrs_vec.iter())
                .map(|(variant, attrs)| {
                    let order = attrs.order.unwrap_or(0);
                    quote! { Self::#variant => #order }
                });

        quote! {
            impl ::enum_companion::EnumCompanionField for #field_enum_name {
                fn name(&self) -> &'static str {
                    match self {
                        #(#name_arms),*
                    }
                }
                fn type_str(&self) -> &'static str {
                    match self {
                        #(#type_str_arms),*
                    }
                }
                fn title(&self) -> &'static str {
                    match self {
                        #(#title_arms),*
                    }
                }
                fn description(&self) -> &'static str {
                    match self {
                        #(#description_arms),*
                    }
                }
                fn order(&self) -> isize {
                    match self {
                        #(#order_arms),*
                    }
                }
            }
        }
    };

    let enum_companion_value_impl = {
        let field_name_arms =
            field_variants
                .iter()
                .zip(field_idents.iter())
                .map(|(variant, ident)| {
                    let ident_str = ident.unraw().to_string();
                    quote! { Self::#variant(_) => #ident_str }
                });

        let type_name_arms = field_variants
            .iter()
            .zip(field_types.iter())
            .map(|(variant, ty)| {
                let type_str = quote!(#ty).to_string();
                quote! { Self::#variant(_) => #type_str }
            });

        quote! {
            impl #impl_generics ::enum_companion::EnumCompanionValue for #value_enum_name #ty_generics #where_clause {
                fn field_name(&self) -> &'static str {
                    match self {
                        #(#field_name_arms),*
                    }
                }
                fn type_name(&self) -> &'static str {
                    match self {
                        #(#type_name_arms),*
                    }
                }
            }
        }
    };

    let trait_impl = if opts.value_fn == "value"
        && opts.update_fn == "update"
        && opts.fields_fn == "fields"
    {
        quote! {
            impl #impl_generics ::enum_companion::EnumCompanionTrait<#field_enum_name, #value_enum_name #ty_generics> for #struct_name #ty_generics #where_clause {
                fn value(&self, field: #field_enum_name) -> #value_enum_name #ty_generics {
                    self.value(field)
                }

                fn update(&mut self, value: #value_enum_name #ty_generics) {
                    self.update(value)
                }

                fn fields() -> &'static [#field_enum_name] {
                    &#field_enum_name::FIELDS
                }

                fn as_values(&self) -> Vec<#value_enum_name #ty_generics> {
                    self.as_values()
                }
            }
        }
    } else {
        quote! {}
    };

    let mut unique_types = std::collections::HashMap::new();
    for (ty, variant) in field_types.iter().zip(field_variants.iter()) {
        let key = quote!(#ty).to_string();
        unique_types
            .entry(key)
            .or_insert_with(|| (ty.clone(), Vec::new()))
            .1
            .push(variant.clone());
    }

    let generic_param_idents: std::collections::HashSet<String> = generics
        .params
        .iter()
        .filter_map(|p| match p {
            syn::GenericParam::Type(ty) => Some(ty.ident.to_string()),
            _ => None,
        })
        .collect();

    let try_from_impls = unique_types.values().filter_map(|(ty, variants)| {
        if type_contains_generic(ty, &generic_param_idents) {
            return None;
        }

        let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
        Some(quote! {
            impl #impl_generics std::convert::TryFrom<#value_enum_name #ty_generics> for #ty #where_clause {
                type Error = #value_enum_name #ty_generics;

                fn try_from(value: #value_enum_name #ty_generics) -> Result<Self, Self::Error> {
                    match value {
                        #(#value_enum_name::#variants(val) => Ok(val)),*,
                        _ => Err(value),
                    }
                }
            }
        })
    });

    let try_into_impls = unique_types.values().filter_map(|(ty, variants)| {
        if type_contains_generic(ty, &generic_param_idents) {
            return None;
        }

        let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
        let arms = variants.iter().map(|variant| {
            quote! {
                #field_enum_name::#variant => Ok(#value_enum_name::#variant(value)),
            }
        });

        Some(quote! {
            impl #impl_generics std::convert::TryFrom<(#field_enum_name, #ty)> for #value_enum_name #ty_generics #where_clause {
                type Error = #field_enum_name;

                fn try_from(value: (#field_enum_name, #ty)) -> Result<Self, Self::Error> {
                    let (field, value) = value;
                    match field {
                        #(#arms)*
                        _ => Err(field),
                    }
                }
            }
        })
    });

    // Generate the final token stream.
    let expanded = quote! {
        /// An enum representing the fields of the struct.
        #[allow(dead_code)]
        #[derive(Copy, Clone, #(#derive_field),*)]
        #serde_field_attr
        #vis enum #field_enum_name {
            #(#field_enum_variants),*
        }

        impl #field_enum_name {
            pub const FIELDS: &'static [#field_enum_name] = &[#(#field_enum_name::#field_variants),*];
        }

        impl std::fmt::Display for #field_enum_name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(
                    f,
                    "{}",
                    <#field_enum_name as ::enum_companion::EnumCompanionField>::name(self)
                )
            }
        }

        #enum_companion_field_impl

        /// An enum representing the values of the struct's fields.
        #[allow(dead_code)]
        #[derive(Clone, #(#derive_value),*)]
        #serde_value_attr
        #vis enum #value_enum_name #ty_generics {
            #(#value_enum_variants),*
        }

        #enum_companion_value_impl

        impl std::str::FromStr for #field_enum_name {
            type Err = String;

            fn from_str(s: &str) -> Result<Self, Self::Err> {
                match s {
                    #(#from_str_arms),*,
                    _ => Err(format!("Invalid field name: {}", s)),
                }
            }
        }

        impl #impl_generics #struct_name #ty_generics #where_clause {
            /// Returns an array of all field enum variants.
            pub fn #fields_fn_name() -> &'static [#field_enum_name] {
                #field_enum_name::FIELDS
            }

            /// Returns a vector of all field values.
            pub fn as_values(&self) -> Vec<#value_enum_name #ty_generics> {
                Self::#fields_fn_name()
                    .iter()
                    .map(|&field| self.#value_fn_name(field))
                    .collect()
            }

            /// Returns the value of a specific field.
            pub fn #value_fn_name(&self, field: #field_enum_name) -> #value_enum_name #ty_generics {
                match field {
                    #(#value_match_arms),*
                }
            }

            /// Updates the value of a specific field.
            pub fn #update_fn_name(&mut self, value: #value_enum_name #ty_generics) {
                match value {
                    #(#update_match_arms),*
                }
            }
        }

        #trait_impl

        #(#try_from_impls)*

        #(#try_into_impls)*
    };

    TokenStream::from(expanded)
}

/// Converts a string to PascalCase.
fn to_pascal_case(s: &str) -> String {
    s.split('_')
        .map(|word| {
            let mut c = word.chars();
            match c.next() {
                None => String::new(),
                Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
            }
        })
        .collect()
}

struct GenericVisitor<'a> {
    generic_params: &'a std::collections::HashSet<String>,
    contains_generic: bool,
}

impl<'ast, 'a> Visit<'ast> for GenericVisitor<'a> {
    fn visit_type_path(&mut self, i: &'ast syn::TypePath) {
        if self.contains_generic {
            return;
        }
        if i.qself.is_none()
            && let Some(segment) = i.path.segments.last()
            && self.generic_params.contains(&segment.ident.to_string())
        {
            self.contains_generic = true;
            return;
        }
        visit::visit_type_path(self, i);
    }
}

fn type_contains_generic(
    ty: &syn::Type,
    generic_params: &std::collections::HashSet<String>,
) -> bool {
    let mut visitor = GenericVisitor {
        generic_params,
        contains_generic: false,
    };
    visitor.visit_type(ty);
    visitor.contains_generic
}