declare_impl 0.8.2

Implementation of the proc macro for the error_set crate.
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
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
#![cfg_attr(not(feature = "dev"), allow(dead_code))]
#![cfg_attr(not(feature = "dev"), allow(unused_variables))]

use std::collections::{HashMap, HashSet};

use proc_macro2::TokenStream;
use quote::{quote, TokenStreamExt};
use syn::{Attribute, Ident, Lit, TypeParam};

use crate::ast::{AstInlineErrorVariantField, Disabled, DisplayAttribute};

/// Expand the [ErrorEnum]s into code.
pub(crate) fn expand(error_enums: Vec<ErrorEnum>) -> TokenStream {
    let mut token_stream = TokenStream::new();
    let mut graph: Vec<ErrorEnumGraphNode> = error_enums
        .into_iter()
        .map(|e| ErrorEnumGraphNode::new(e))
        .collect();

    // build a graph of valid conversion `From`'s
    for building_index in 0..graph.len() {
        'next_enum: for checking_index in 0..graph.len() {
            if checking_index == building_index {
                continue;
            }

            let mut variant_mappings = Vec::new();
            'look_for_next_variant_match: for (checking_variant_index, checking_variant) in graph
                [checking_index]
                .error_enum
                .error_variants
                .iter()
                .enumerate()
            {
                for (building_variant_index, building_variant) in graph[building_index]
                    .error_enum
                    .error_variants
                    .iter()
                    .enumerate()
                {
                    if is_conversion_target(checking_variant, building_variant) {
                        variant_mappings.push((checking_variant_index, building_variant_index));
                        continue 'look_for_next_variant_match;
                    }
                }
                continue 'next_enum;
            }
            graph[building_index]
                .froms
                .push((checking_index, variant_mappings));
        }
    }

    for error_enum_node in graph.iter() {
        add_code_for_node(error_enum_node, &*graph, &mut token_stream);
    }
    token_stream
}

fn add_code_for_node(
    error_enum_node: &ErrorEnumGraphNode,
    graph: &[ErrorEnumGraphNode],
    token_stream: &mut TokenStream,
) {
    add_enum(error_enum_node, token_stream);
    impl_error(error_enum_node, token_stream);
    impl_display(error_enum_node, token_stream);
    impl_froms(error_enum_node, graph, token_stream);
}

fn add_enum(error_enum_node: &ErrorEnumGraphNode, token_stream: &mut TokenStream) {
    let ErrorEnumGraphNode {
        error_enum,
        froms: _,
    } = error_enum_node;

    let enum_name = &error_enum.error_name;
    let error_variants = &error_enum.error_variants;
    #[cfg(feature = "dev")]
    assert!(
        !error_variants.is_empty(),
        "Error variants should not be empty"
    );
    let mut error_variant_tokens = TokenStream::new();
    for variant in error_variants {
        match variant {
            ErrorVariant::Named(named) => {
                let attributes = &named.attributes;
                let name = &named.name;
                error_variant_tokens.append_all(quote::quote! {
                    #(#attributes)*
                    #name,
                });
            }
            ErrorVariant::Struct(r#struct) => {
                let attributes = &r#struct.attributes;
                let name = &r#struct.name;
                let fields = &r#struct.fields;
                let field_names = fields.iter().map(|e| &e.name);
                let field_types = fields.iter().map(|e| &e.r#type);
                error_variant_tokens.append_all(quote::quote! {
                    #(#attributes)*
                    #name {
                        #(#field_names : #field_types),*
                    },
                });
            }
            ErrorVariant::SourceStruct(source_struct) => {
                let attributes = &source_struct.attributes;
                let name = &source_struct.name;
                let fields = &source_struct.fields;
                let field_names = fields.iter().map(|e| &e.name);
                let field_types = fields.iter().map(|e| &e.r#type);
                let source_type = &source_struct.source_type;
                error_variant_tokens.append_all(quote::quote! {
                    #(#attributes)*
                    #name {
                        source: #source_type,
                        #(#field_names : #field_types),*
                    },
                });
            }
            ErrorVariant::SourceTuple(source_tuple) => {
                let attributes = &source_tuple.attributes;
                let name = &source_tuple.name;
                let source_type = &source_tuple.source_type;
                error_variant_tokens.append_all(quote::quote! {
                    #(#attributes)*
                    #name(#source_type),
                });
            }
        }
    }
    let attributes = &error_enum.attributes;
    let (impl_generics, ty_generics) = generic_tokens(&error_enum.generics);
    let debug = if error_enum.disabled.debug {
        quote! {}
    } else {
        quote! { #[derive(Debug)] }
    };
    token_stream.append_all(quote::quote! {
        #(#attributes)*
        #debug
        pub enum #enum_name #impl_generics {
            #error_variant_tokens
        }
    });
}

fn impl_error(error_enum_node: &ErrorEnumGraphNode, token_stream: &mut TokenStream) {
    let ErrorEnumGraphNode {
        error_enum,
        froms: _,
    } = error_enum_node;
    if error_enum.disabled.error {
        return;
    }
    let enum_name = &error_enum.error_name;
    let mut source_match_branches = TokenStream::new();
    let mut has_source_match_branches = false;
    for variant in &error_enum.error_variants {
        if is_source_tuple_type(variant) {
            has_source_match_branches = true;
            let name = &variant.name();
            source_match_branches.append_all(quote::quote! {
                #enum_name::#name(ref source) => source.source(),
            });
        } else if is_source_struct_type(variant) {
            has_source_match_branches = true;
            let name = &variant.name();
            source_match_branches.append_all(quote::quote! {
                #enum_name::#name { ref source, .. } => source.source(),
            });
        }
    }
    let mut error_inner = TokenStream::new();
    if has_source_match_branches {
        error_inner.append_all(quote::quote! {
            fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
                match self {
                    #source_match_branches
                    #[allow(unreachable_patterns)]
                    _ => None,
                }
            }
        });
    }
    let (impl_generics, ty_generics) = generic_tokens(&error_enum.generics);
    token_stream.append_all(quote::quote! {
        #[allow(unused_qualifications)]
        impl #impl_generics core::error::Error for #enum_name #ty_generics {
            #error_inner
        }
    });
}

fn impl_display(error_enum_node: &ErrorEnumGraphNode, token_stream: &mut TokenStream) {
    let ErrorEnumGraphNode {
        error_enum,
        froms: _,
    } = error_enum_node;
    if error_enum.disabled.display {
        return;
    }
    let enum_name = &error_enum.error_name;
    let error_variants = &error_enum.error_variants;
    #[cfg(feature = "dev")]
    assert!(
        !error_variants.is_empty(),
        "Error variants should not be empty"
    );
    let mut error_variant_tokens = TokenStream::new();
    for variant in error_variants {
        let right_side: TokenStream;
        let name = &variant.name();
        if let Some(display) = &variant.display() {
            let tokens = &display.tokens;
            // e.g. `opaque`
            if is_opaque(tokens.clone()) {
                right_side = quote::quote! {
                    write!(f, "{}", concat!(stringify!(#enum_name), "::", stringify!(#name)))
                };
            } else if let Some(string) = extract_string_if_str_literal(tokens.clone()) {
                // e.g. `"{}"`
                if is_format_str(&string) {
                    if is_source_tuple_type(variant) {
                        right_side = quote::quote! {
                            write!(f, #tokens, source)
                        };
                    } else {
                        right_side = quote::quote! {
                            write!(f, #tokens)
                        };
                    }
                } else {
                    // e.g. `"literal str"`
                    right_side = quote::quote! {
                        write!(f, "{}", #tokens)
                    };
                }
            } else {
                // e.g. `"field: {}", source.field`
                right_side = quote::quote! {
                    write!(f, #tokens)
                };
            }
        } else {
            if is_source_tuple_type(variant) {
                right_side = quote::quote! {
                    write!(f, "{}", source)
                };
            } else {
                right_side = quote::quote! {
                    write!(f, "{}", concat!(stringify!(#enum_name), "::", stringify!(#name)))
                };
            }
        }

        match variant {
            ErrorVariant::Named(_) => {
                error_variant_tokens.append_all(quote::quote! {
                    #enum_name::#name =>  #right_side,
                });
            }
            ErrorVariant::Struct(r#struct) => {
                let field_names = r#struct.fields.iter().map(|e| &e.name);
                error_variant_tokens.append_all(quote::quote! {
                    #enum_name::#name { #(ref #field_names),*  } =>  #right_side,
                });
            }
            ErrorVariant::SourceStruct(source_struct) => {
                let field_names = source_struct.fields.iter().map(|e| &e.name);
                error_variant_tokens.append_all(quote::quote! {
                    #enum_name::#name { ref source, #(ref #field_names),* } =>  #right_side,
                });
            }
            ErrorVariant::SourceTuple(_) => {
                error_variant_tokens.append_all(quote::quote! {
                    #enum_name::#name(ref source) =>  #right_side,
                });
            }
        }
    }
    let (impl_generics, ty_generics) = generic_tokens(&error_enum.generics);
    token_stream.append_all(quote::quote! {
        impl #impl_generics core::fmt::Display for #enum_name #ty_generics {
            #[inline]
            fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
                match *self {
                    #error_variant_tokens
                }
            }
        }
    });
}

fn impl_froms(
    error_enum_node: &ErrorEnumGraphNode,
    graph: &[ErrorEnumGraphNode],
    token_stream: &mut TokenStream,
) {
    let error_enum = &error_enum_node.error_enum;
    let from = &error_enum.disabled.from;
    if from.as_ref().is_some_and(|e| e.is_empty()) {
        return;
    }
    let temp = Vec::new();
    let froms_to_disable = from.as_ref().unwrap_or(&temp);
    let froms_to_disable_idents = froms_to_disable
        .iter()
        .flat_map(|e| e.path.get_ident())
        .collect::<Vec<_>>();
    let error_enum_name = &error_enum.error_name;

    for (from_error_enum, variant_mappings) in error_enum_node.resolved_froms(graph) {
        if froms_to_disable_idents.contains(&&from_error_enum.error_name) {
            continue;
        }
        let mut error_branch_tokens = TokenStream::new();
        let from_error_enum_name = &from_error_enum.error_name;
        for (from_error_enum_variant, error_enum_variant) in variant_mappings {
            #[cfg(feature = "dev")]
            {
                assert!(
                    from_error_enum
                        .error_variants
                        .iter()
                        .any(|e| e.name() == from_error_enum_variant.name()),
                    "Variant not found in from error enum"
                );
                assert!(
                    error_enum
                        .error_variants
                        .iter()
                        .any(|e| e.name() == error_enum_variant.name()),
                    "Variant not found in error enum"
                );
                let from = from_error_enum_variant.name();
                let to = error_enum_variant.name();
                assert!(
                    is_conversion_target(from_error_enum_variant, error_enum_variant),
                    "Not a valid conversion target\n\nfrom:\n\n{from}\n\nto:\n\n{to}"
                );
            }
            let arm: Option<TokenStream> = match (from_error_enum_variant, error_enum_variant) {
                (ErrorVariant::Named(this), ErrorVariant::Named(that)) => Some(name_to_name(
                    from_error_enum_name,
                    &this.name,
                    error_enum_name,
                    &that.name,
                )),
                (ErrorVariant::Named(this), ErrorVariant::Struct(that)) => None,
                (ErrorVariant::Named(this), ErrorVariant::SourceStruct(that)) => None,
                (ErrorVariant::Named(this), ErrorVariant::SourceTuple(that)) => None,
                (ErrorVariant::Struct(this), ErrorVariant::Named(that)) => None,
                (ErrorVariant::Struct(this), ErrorVariant::Struct(that)) => Some(struct_to_struct(
                    from_error_enum_name,
                    &this.name,
                    &this.fields,
                    error_enum_name,
                    &that.name,
                    &that.fields,
                )),
                (ErrorVariant::Struct(this), ErrorVariant::SourceStruct(that)) => None,
                (ErrorVariant::Struct(this), ErrorVariant::SourceTuple(that)) => None,
                (ErrorVariant::SourceStruct(this), ErrorVariant::Named(that)) => None,
                (ErrorVariant::SourceStruct(this), ErrorVariant::Struct(that)) => None,
                (ErrorVariant::SourceStruct(this), ErrorVariant::SourceStruct(that)) => {
                    Some(source_struct_to_source_struct(
                        from_error_enum_name,
                        &this.name,
                        &this.fields,
                        error_enum_name,
                        &that.name,
                        &that.fields,
                    ))
                }
                (ErrorVariant::SourceStruct(this), ErrorVariant::SourceTuple(that)) => {
                    Some(source_struct_to_source_tuple(
                        from_error_enum_name,
                        &this.name,
                        &this.fields,
                        error_enum_name,
                        &that.name,
                    ))
                }
                (ErrorVariant::SourceTuple(this), ErrorVariant::Named(that)) => None,
                (ErrorVariant::SourceTuple(this), ErrorVariant::Struct(that)) => None,
                (ErrorVariant::SourceTuple(this), ErrorVariant::SourceStruct(that)) => {
                    if that.fields.is_empty() {
                        Some(source_tuple_to_source_only_struct(
                            from_error_enum_name,
                            &this.name,
                            error_enum_name,
                            &that.name,
                        ))
                    } else {
                        None
                    }
                }
                (ErrorVariant::SourceTuple(this), ErrorVariant::SourceTuple(that)) => {
                    Some(source_tuple_to_source_tuple(
                        from_error_enum_name,
                        &this.name,
                        error_enum_name,
                        &that.name,
                    ))
                }
            };
            if let Some(arm) = arm {
                error_branch_tokens.append_all(arm);
            }
        }
        // Dev Note: If from has generics and they are not the same as target's, then there is no guarantee that `impl_generics`
        // will contain all of and the correct generics definitions that are for `from_ty_generics`. Merging may cause
        // conflicts. This guard likely won't ever be removed since the correct mixture of generics may be
        // impossible to determine without the user explicitly specifying. Even if this guard does not hold,
        // an "unwanted" (but no compile error) `From` may be generated. This is an edge case and we are
        // being optimistic, so we don't just not implement `From` for all generics. But a user can opt-out
        // with `#[disable(From(..))]`
        if !from_error_enum.generics.is_empty() && error_enum.generics != from_error_enum.generics {
            continue;
        }
        let (impl_generics, ty_generics) = generic_tokens(&error_enum.generics);
        let (from_impl_generics, from_ty_generics) = generic_tokens(&from_error_enum.generics);
        token_stream.append_all(quote::quote! {
            impl #impl_generics From<#from_error_enum_name #from_ty_generics> for #error_enum_name #ty_generics {
                fn from(error: #from_error_enum_name #from_ty_generics) -> Self {
                    match error {
                        #error_branch_tokens
                    }
                }
            }
        });
    }

    // Do not impl `From` for source where source is the same between multiple variants
    let mut source_type_to_error_variants = HashMap::new();
    let mut all_source_types = HashSet::new();
    for error_variant in error_enum.error_variants.iter() {
        if let Some(source_type) = error_variant.source_type() {
            if froms_to_disable.contains(source_type) {
                continue;
            }
            if all_source_types.contains(source_type) {
                source_type_to_error_variants.remove(source_type);
            } else {
                all_source_types.insert(source_type);
                source_type_to_error_variants.insert(source_type, error_variant);
            }
        }
    }

    // Add `From`'s for all valid variants that are wrappers around source errors.
    for error_variant in source_type_to_error_variants.values() {
        let source_type = error_variant.source_type();
        if is_source_tuple_type(error_variant) {
            let (impl_generics, ty_generics) = generic_tokens(&error_enum.generics);
            let variant_name = &error_variant.name();
            token_stream.append_all(quote::quote! {
                impl #impl_generics From<#source_type> for #error_enum_name #ty_generics {
                    fn from(error: #source_type) -> Self {
                        #error_enum_name::#variant_name(error)
                    }
                }
            });
        } else if is_source_only_struct_type(error_variant) {
            let (impl_generics, ty_generics) = generic_tokens(&error_enum.generics);
            let variant_name = &error_variant.name();
            token_stream.append_all(quote::quote! {
                impl #impl_generics From<#source_type> for #error_enum_name #ty_generics {
                    fn from(error: #source_type) -> Self {
                        #error_enum_name::#variant_name { source: error }
                    }
                }
            });
        }
    }
}
//************************************************************************//

fn name_to_name(
    this_enum_name: &Ident,
    this_enum_variant_name: &Ident,
    that_enum_name: &Ident,
    that_enum_variant_name: &Ident,
) -> TokenStream {
    quote::quote! {
        #this_enum_name::#this_enum_variant_name =>  #that_enum_name::#that_enum_variant_name,
    }
}

fn struct_to_struct(
    this_enum_name: &Ident,
    this_variant_name: &Ident,
    this_enum_fields: &Vec<AstInlineErrorVariantField>,
    that_enum_name: &Ident,
    that_variant_name: &Ident,
    that_enum_fields: &Vec<AstInlineErrorVariantField>,
) -> TokenStream {
    let this_field_names = this_enum_fields.iter().map(|e| &e.name);
    let that_field_names = that_enum_fields.iter().map(|e| &e.name);
    quote::quote! {
        #this_enum_name::#this_variant_name { #(#this_field_names),*  } =>  #that_enum_name::#that_variant_name { #(#that_field_names),*  },
    }
}

fn source_tuple_to_source_tuple(
    this_enum_name: &Ident,
    this_enum_variant_name: &Ident,
    that_enum_name: &Ident,
    that_enum_variant_name: &Ident,
) -> TokenStream {
    quote::quote! {
        #this_enum_name::#this_enum_variant_name(source) =>  #that_enum_name::#that_enum_variant_name(source),
    }
}

fn source_tuple_to_source_only_struct(
    this_enum_name: &Ident,
    this_enum_variant_name: &Ident,
    that_enum_name: &Ident,
    that_enum_variant_name: &Ident,
) -> TokenStream {
    quote::quote! {
        #this_enum_name::#this_enum_variant_name(source) =>  #that_enum_name::#that_enum_variant_name { source },
    }
}

fn source_struct_to_source_tuple(
    this_enum_name: &Ident,
    this_enum_variant_name: &Ident,
    this_enum_fields: &Vec<AstInlineErrorVariantField>,
    that_enum_name: &Ident,
    that_enum_variant_name: &Ident,
) -> TokenStream {
    quote::quote! {
        #this_enum_name::#this_enum_variant_name { source, .. } =>  #that_enum_name::#that_enum_variant_name(source),
    }
}

fn source_struct_to_source_struct(
    this_enum_name: &Ident,
    this_enum_variant_name: &Ident,
    this_enum_fields: &Vec<AstInlineErrorVariantField>,
    that_enum_name: &Ident,
    that_variant_name: &Ident,
    that_enum_fields: &Vec<AstInlineErrorVariantField>,
) -> TokenStream {
    let this_field_names = this_enum_fields.iter().map(|e| &e.name);
    let that_field_names = that_enum_fields.iter().map(|e| &e.name);
    quote::quote! {
        #this_enum_name::#this_enum_variant_name { source, #(#this_field_names),*  } =>  #that_enum_name::#that_variant_name { source, #(#that_field_names),* },
    }
}

pub(crate) trait Common {
    fn attributes(&self) -> &Vec<Attribute>;
    fn display(&self) -> Option<&DisplayAttribute>;
    fn name(&self) -> &Ident;
    fn fields(&self) -> Option<&Vec<AstInlineErrorVariantField>>;
    fn source_type(&self) -> Option<&syn::TypePath>;
}

#[derive(Clone)]
pub(crate) enum ErrorVariant {
    /// e.g. `ErrorVariantNamed,`
    Named(Named),
    /// e.g. `ErrorVariantNamed {...}`
    Struct(Struct),
    /// e.g. `ErrorVariantNamed(std::io::Error) {...}`
    SourceStruct(SourceStruct),
    /// e.g. `ErrorVariantNamed(std::io::Error)`
    SourceTuple(SourceTuple),
}

impl Common for ErrorVariant {
    fn attributes(&self) -> &Vec<Attribute> {
        match self {
            ErrorVariant::Named(e) => e.attributes(),
            ErrorVariant::Struct(e) => e.attributes(),
            ErrorVariant::SourceStruct(e) => e.attributes(),
            ErrorVariant::SourceTuple(e) => e.attributes(),
        }
    }
    fn display(&self) -> Option<&DisplayAttribute> {
        match self {
            ErrorVariant::Named(e) => e.display(),
            ErrorVariant::Struct(e) => e.display(),
            ErrorVariant::SourceStruct(e) => e.display(),
            ErrorVariant::SourceTuple(e) => e.display(),
        }
    }
    fn name(&self) -> &Ident {
        match self {
            ErrorVariant::Named(e) => e.name(),
            ErrorVariant::Struct(e) => e.name(),
            ErrorVariant::SourceStruct(e) => e.name(),
            ErrorVariant::SourceTuple(e) => e.name(),
        }
    }
    fn fields(&self) -> Option<&Vec<AstInlineErrorVariantField>> {
        match self {
            ErrorVariant::Named(e) => e.fields(),
            ErrorVariant::Struct(e) => e.fields(),
            ErrorVariant::SourceStruct(e) => e.fields(),
            ErrorVariant::SourceTuple(e) => e.fields(),
        }
    }
    fn source_type(&self) -> Option<&syn::TypePath> {
        match self {
            ErrorVariant::Named(e) => e.source_type(),
            ErrorVariant::Struct(e) => e.source_type(),
            ErrorVariant::SourceStruct(e) => e.source_type(),
            ErrorVariant::SourceTuple(e) => e.source_type(),
        }
    }
}

#[derive(Clone)]
pub(crate) struct Named {
    pub(crate) attributes: Vec<Attribute>,
    pub(crate) display: Option<DisplayAttribute>,
    pub(crate) name: Ident,
}

impl Common for Named {
    fn attributes(&self) -> &Vec<Attribute> {
        &self.attributes
    }
    fn display(&self) -> Option<&DisplayAttribute> {
        self.display.as_ref()
    }
    fn name(&self) -> &Ident {
        &self.name
    }
    fn fields(&self) -> Option<&Vec<AstInlineErrorVariantField>> {
        None
    }
    fn source_type(&self) -> Option<&syn::TypePath> {
        None
    }
}

#[derive(Clone)]
pub(crate) struct Struct {
    pub(crate) attributes: Vec<Attribute>,
    pub(crate) display: Option<DisplayAttribute>,
    pub(crate) name: Ident,
    // Dev Note: This field will never be empty. Otherwise it should just be a [Named]
    pub(crate) fields: Vec<AstInlineErrorVariantField>,
}

impl Common for Struct {
    fn attributes(&self) -> &Vec<Attribute> {
        &self.attributes
    }
    fn display(&self) -> Option<&DisplayAttribute> {
        self.display.as_ref()
    }
    fn name(&self) -> &Ident {
        &self.name
    }
    fn fields(&self) -> Option<&Vec<AstInlineErrorVariantField>> {
        Some(&self.fields)
    }
    fn source_type(&self) -> Option<&syn::TypePath> {
        None
    }
}

#[derive(Clone)]
pub(crate) struct SourceStruct {
    pub(crate) attributes: Vec<Attribute>,
    pub(crate) display: Option<DisplayAttribute>,
    pub(crate) name: Ident,
    pub(crate) source_type: syn::TypePath,
    // Dev Note: This field can be empty
    pub(crate) fields: Vec<AstInlineErrorVariantField>,
}

impl Common for SourceStruct {
    fn attributes(&self) -> &Vec<Attribute> {
        &self.attributes
    }
    fn display(&self) -> Option<&DisplayAttribute> {
        self.display.as_ref()
    }
    fn name(&self) -> &Ident {
        &self.name
    }
    fn fields(&self) -> Option<&Vec<AstInlineErrorVariantField>> {
        Some(&self.fields)
    }
    fn source_type(&self) -> Option<&syn::TypePath> {
        Some(&self.source_type)
    }
}

#[derive(Clone)]
pub(crate) struct SourceTuple {
    pub(crate) attributes: Vec<Attribute>,
    pub(crate) display: Option<DisplayAttribute>,
    pub(crate) name: Ident,
    pub(crate) source_type: syn::TypePath,
}

impl Common for SourceTuple {
    fn attributes(&self) -> &Vec<Attribute> {
        &self.attributes
    }
    fn display(&self) -> Option<&DisplayAttribute> {
        self.display.as_ref()
    }
    fn name(&self) -> &Ident {
        &self.name
    }
    fn fields(&self) -> Option<&Vec<AstInlineErrorVariantField>> {
        None
    }
    fn source_type(&self) -> Option<&syn::TypePath> {
        Some(&self.source_type)
    }
}

//************************************************************************//
#[derive(Clone)]
struct ErrorEnumGraphNode {
    pub(crate) error_enum: ErrorEnum,
    /// nodes where this error enum can be converted to the other error enum
    /// 0: index of target enum in graph
    /// 1: variant mapping
    ///   0: the from's error_variants's index
    ///   1: this's error_variants's index
    pub(crate) froms: Vec<(usize, Vec<(usize, usize)>)>,
}

impl PartialEq for ErrorEnumGraphNode {
    fn eq(&self, other: &Self) -> bool {
        self.error_enum == other.error_enum
    }
}

impl ErrorEnumGraphNode {
    pub(crate) fn new(node: ErrorEnum) -> ErrorEnumGraphNode {
        ErrorEnumGraphNode {
            error_enum: node,
            froms: Vec::new(),
        }
    }

    /// Returns an iterator of all the froms of this error enum. And the variant mappings from this to that.
    pub(crate) fn resolved_froms<'a>(
        &'a self,
        graph: &'a [ErrorEnumGraphNode],
    ) -> impl Iterator<Item = (&'a ErrorEnum, Vec<(&'a ErrorVariant, &'a ErrorVariant)>)> {
        self.froms.iter().map(|e| {
            let from = &graph[e.0];
            let variant_mappings =
                e.1.iter()
                    .map(|(from_index, this_index)| {
                        (
                            &from.error_enum.error_variants[*from_index],
                            &self.error_enum.error_variants[*this_index],
                        )
                    })
                    .collect::<Vec<_>>();
            (&from.error_enum, variant_mappings)
        })
    }
}

#[derive(Clone)]
pub(crate) struct ErrorEnum {
    pub(crate) attributes: Vec<Attribute>,
    pub(crate) error_name: Ident,
    pub(crate) generics: Vec<TypeParam>,
    pub(crate) disabled: Disabled,
    pub(crate) error_variants: Vec<ErrorVariant>,
}

impl core::hash::Hash for ErrorEnum {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.error_name.hash(state);
    }
}

impl Eq for ErrorEnum {}

impl PartialEq for ErrorEnum {
    fn eq(&self, other: &Self) -> bool {
        self.error_name == other.error_name
    }
}

//************************************************************************//

fn extract_string_if_str_literal(input: TokenStream) -> Option<String> {
    if let Ok(expr) = syn::parse2::<Lit>(input) {
        if let Lit::Str(lit) = expr {
            return Some(lit.value());
        }
    }
    None
}

// Dev Note: naive implementation.
fn is_format_str(input: &str) -> bool {
    let mut interpolation_candidate_found = false;
    let mut last_char = 'a';

    let mut start_count = 0;
    let mut end_count = 0;

    for c in input.chars() {
        if c == '{' {
            if last_char == '{' {
                last_char = 'a';
                start_count -= 1;
                continue;
            }
            start_count += 1;
        } else if c == '}' {
            if last_char == '}' {
                last_char = 'a';
                end_count -= 1;
                continue;
            }
            end_count += 1;
            if start_count == end_count {
                interpolation_candidate_found = true;
            }
        }
        last_char = c;
    }
    return interpolation_candidate_found && start_count == end_count;
}

fn is_opaque(input: TokenStream) -> bool {
    if let Ok(ident) = syn::parse2::<Ident>(input) {
        ident == "opaque"
    } else {
        false
    }
}

//************************************************************************//

fn generic_tokens(generics: &Vec<TypeParam>) -> (Option<TokenStream>, Option<TokenStream>) {
    if generics.is_empty() {
        return (None, None);
    }
    let impl_clause = quote! {<#(#generics),*>};

    let names = generics.iter().map(|e| &e.ident);
    let ty_clause = quote! {<#(#names),*>};

    (Some(impl_clause), Some(ty_clause))
}

//************************************************************************//

pub(crate) fn is_source_tuple_type(error_variant: &ErrorVariant) -> bool {
    return error_variant.source_type().is_some() && error_variant.fields().is_none();
}

pub(crate) fn is_source_only_struct_type(error_variant: &ErrorVariant) -> bool {
    return error_variant.source_type().is_some()
        && error_variant
            .fields()
            .as_ref()
            .is_some_and(|e| e.is_empty());
}

pub(crate) fn is_source_struct_type(error_variant: &ErrorVariant) -> bool {
    return error_variant.source_type().is_some() && error_variant.fields().as_ref().is_some();
}

/// To determine if [this] can be converted into [that] without dropping values.
/// Ignoring backtrace (since this is generated in the `From` impl if missing) and display.
/// This does not mean [this] is a subset of [that].
/// Why do they need to be exact?
/// e.g.
/// ```
/// X {
///   a: String,
///   b: u32,
/// }
/// ```
/// The above can be converted to the below, by droping the `b`. Even though the below could be considered a "subset".
/// ```
/// Y {
///   a: String
/// }
/// ```
/// If the below was also in the target enum, it would also be valid conversion target
/// ```
/// Z {
///  b: u32
/// }
/// ```
/// Thus, the names and shapes must be exactly the same to avoid this.
/// Note, there can multiple source tuples or sources only structs with the same wrapped error types (different names).
/// The first that is encountered becomes the `From` impl of that source error type.
/// To ensure the correct one is selected, pay attention to `X = A || B` ordering
/// or define your own `X = { IoError(std::io::Error) } || A || B`
///
/// Another example:
/// ```
///  N1 {
///     field: i32
///  }
/// ```
/// ==
/// ```
/// N1 {
///     field: i32
///  }
/// ```
/// !=
/// ```
/// N2 {
///     field: i32
///  }
/// ```
pub(crate) fn is_conversion_target(this: &ErrorVariant, that: &ErrorVariant) -> bool {
    return match (&this.source_type(), &that.source_type()) {
        (Some(this_source_type), Some(other_source_type)) => {
            this_source_type.path == other_source_type.path
                && this.name() == that.name()
                && this.fields() == that.fields()
        }
        (None, None) => this.name() == that.name() && this.fields() == that.fields(),
        _ => false,
    };
}