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
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::{quote, TokenStreamExt};
use syn::fold::{self, Fold};
use syn::token::Comma;
use syn::{
    parse_macro_input, parse_quote, Attribute, Expr, ExprMatch, FieldValue, Fields, Ident, Item,
    ItemFn, ItemStruct, LitStr, ReturnType, Type, Variant,
};

/// Struct to handle the folding of the ItemFn.
/// Holds the return type and message for use by the fold functions.
struct ContextMsg {
    m: LitStr,
    rettype: Box<Type>,
    has_ok: bool,
}

impl ContextMsg {
    fn new(m: LitStr, rettype: Box<Type>) -> Self {
        ContextMsg {
            m,
            rettype,
            has_ok: false,
        }
    }
}

// The Fold trait is used to inject the error handling into the the source code.
// The Fold will change this function...
// #[context("context message")]
// fn basic_exampleerror() -> Result<(), ExampleError> {
//     if io_error()? {
//         return example_error().map_err(|e| e.msg("msgs are great"));
//     }
//     example_error()
// }
//
// into...
// fn basic_exampleerror() -> Result<(), ExampleError> {
//     if hb_error::ConvertInto::Result<(), ExampleError>::convert(io_error()).map_err(|er| er.make_inner().msg("context message")? {
//         return hb_error::ConvertInto::Result<(), ExampleError>::convert(example_error().map_err(|e| e.msg("msgs are great"))).map_err(|er| er.make_inner().msg("context message");
//     }
//     example_error()
// }
impl Fold for ContextMsg {
    fn fold_expr(&mut self, e: Expr) -> Expr {
        match e {
            Expr::Return(mut rexpr) => {
                match rexpr.expr {
                    Some(ex) => {
                        let m = &self.m;
                        let rettype = &self.rettype;
                        if m.value().contains('{') {
                            let mut msg_args = syn::punctuated::Punctuated::<Expr, Comma>::new();
                            let str = m.value();
                            let mut brace_contents: Vec<String> = vec![];
                            let mut in_brace = false;
                            let mut buf = String::new();
                            let mut out_str = String::new();
                            for c in str.chars() {
                                if c == '{' {
                                    in_brace = true;
                                    out_str.push(c);
                                } else if c == '}' {
                                    if buf.len() > 0 {
                                        brace_contents.push(buf);
                                        buf = String::new();
                                    }
                                    in_brace = false;
                                    out_str.push(c);
                                } else if in_brace {
                                    buf.push(c);
                                } else {
                                    out_str.push(c);
                                }
                            }
                            for content in brace_contents {
                                msg_args.push(
                                    syn::parse_str::<Expr>(&content).expect(
                                        format!("cannot convert {} into an expression.", content)
                                            .as_str(),
                                    ),
                                );
                            }
                            msg_args.insert(0, parse_quote!(#out_str));
                            rexpr.expr = Some(
                                parse_quote!(hb_error::ConvertInto::<#rettype>::convert(#ex).map_err(|er| er.make_inner().msg(format!(#msg_args)))),
                            );
                        } else {
                            rexpr.expr = Some(
                                parse_quote!(hb_error::ConvertInto::<#rettype>::convert(#ex).map_err(|er| er.make_inner().msg(#m))),
                            );
                        }
                    }
                    None => (),
                }
                fold::fold_expr(self, Expr::Return(rexpr))
            }
            Expr::Try(mut texpr) => {
                let ex = texpr.expr;
                let m = &self.m;
                texpr.expr = parse_quote!(#ex.make_inner().msg(#m));
                Expr::Try(texpr)
            }
            Expr::Path(mut exprpath) => match exprpath.path.is_ident("Ok") {
                true => {
                    exprpath
                        .path
                        .segments
                        .insert(0, parse_quote!(HbErrorContextType));
                    self.has_ok = true;
                    Expr::Path(exprpath)
                }
                false => Expr::Path(exprpath),
            },
            _ => fold::fold_expr(self, e),
        }
    }
}

/// Converts Errors returned by the function into the correct type for the
/// function as well adding a context message provided. There are many different situations that
/// need to be handled. The context message can also have a special format to use variables
/// in the context message.
/// # The context message format
/// The context message is treated as string, but it also allows the use of curly braces to inject
/// variables into the message. In the example below the msg parameter to the function is injected
/// into the context message.
/// ```
/// #[context("could not find message {msg}")]
/// fn find_msg(msg: String) -> Result<bool, FindError> {...}
/// ```
/// # Return expressions and Fall Through values`
/// Return expressions are modified to convert the returned result into the type expected by the
/// function using the hb_error::ConvertInto function. In addition, the error is also given the provided context message.
/// ```
///     return example_error();
/// ```
/// into...
/// ```
///     return hb_error::ConvertInto::<Result<(), ExampleError>>::convert(example_error()).map_err(|e| e.msg("some context message"));
/// ```
/// Similarly fall through values are handled similarly but with extra scaffolding around it so that
/// the compiler knows what type is expected in the block of the function and can show appropriate
/// error messages.
/// ```
/// fn something() -> Result<(), ExampleError> {
///     example_error
/// }
/// ```
/// into...
/// ```
/// fn something() -> Result<(), ExampleError> {
///     #[allow(unreachable_code)]
///     let ret: Result<(), ExampleError> = {
///         #[warn(unreachable_code)]
///         example_error
///     };
///     #[allow(unreachable_code)]
///     ret.map_err(|er| er.make_inner().msg("Some context message."))
/// }
/// ```
/// # Try expressions (? operator)
/// Try expressions are modified to convert the returned result into the type expected by the
/// function using the hb_error::ConvertInto function. In addition, the error is also given the provided context message.
/// ```
///     let a = example_error()?;
/// ```
/// into...
/// ```
///     let a = example_error().make_inner().msg("some context message")?;
/// ```
/// # Special Handling for Ok
/// The Ok return type needs special handling because the compiler cannot infer the return type with
/// the extra scaffolding that has been put around the main block of the function. To compensate for
/// this the Ok value is given a full path qualifier. As the path syntax changes based on how it is
/// used, a alias is defined at the begining of the function (HbErrorContextType).
/// ```
///     Ok(())
/// ```
/// into...
/// ```
///     type HbErrorContextType = Result<(), ExampleError>;
///     HbErrorContextType::Ok(())
/// ```
#[proc_macro_attribute]
pub fn context(args: TokenStream, input: TokenStream) -> TokenStream {
    // convert the input TokenStream into a ItemFn syntax object
    let input = parse_macro_input!(input as ItemFn);
    let mut message;
    // Extract the return type from the function signature
    let gen = input.sig.generics.clone();
    if let ReturnType::Type(_, r) = &input.sig.output {
        // Read the args provided as a LitStr ie contents of the () after context in the attibute
        // Then create a ContextMsg object
        message = ContextMsg::new(parse_macro_input!(args as LitStr), r.clone());
    } else {
        // If the return type is the default return type () then skip processing
        return TokenStream::from(quote! {#input});
    }
    // Handle Return and ? by folding the ItemFn syntax tree with the ContextMsg object
    let mut output = message.fold_item_fn(input);
    // Wrap the context of the function to grab the fall through Result then add the context
    // onto the any errors with map_err
    let rettype = message.rettype.clone();
    let mut block = output.block.clone();
    if message.has_ok {
        block
            .stmts
            .insert(0, parse_quote! { type HbErrorContextType #gen = #rettype; });
    }
    let msg = message.m.clone();
    output.block = parse_quote! {
        {
            #[allow(unreachable_code)]
            let ret: #rettype = {
                #[warn(unreachable_code)]
                #block
            };
            #[allow(unreachable_code)]
            ret.map_err(|er| er.make_inner().msg(#msg))
        }
    };
    // Convert the SyntaxTree back into a TokenTree
    TokenStream::from(quote! {#output})
}

#[proc_macro_attribute]
pub fn context_doc(_: TokenStream, input: TokenStream) -> TokenStream {
    // convert the input TokenStream into a ItemFn syntax object
    let input = parse_macro_input!(input as ItemFn);
    let gen = input.sig.generics.clone();
    let mut message;
    let doc_comments: Vec<Attribute> = input
        .attrs
        .iter()
        .filter(|a| a.path.is_ident("doc"))
        .map(|a| a.clone())
        .collect();
    if doc_comments.len() == 0 || doc_comments.len() > 1 {
        panic!("context_doc only works with single line doc comments.")
    }
    let tokens = doc_comments.first().unwrap().tokens.clone();
    let mut msg = format!("{}", tokens);
    msg = msg[3..msg.len() - 1].trim().to_owned();
    msg = msg.replace("\\'", "'");
    msg = msg.replace("[", "'{");
    msg = msg.replace("]", "}'");
    // Extract the return type from the function signature
    if let ReturnType::Type(_, r) = &input.sig.output {
        // Read the args provided as a LitStr ie contents of the () after context in the attibute
        // Then create a ContextMsg object
        message = ContextMsg::new(LitStr::new(&msg, Span::mixed_site()), r.clone());
        //message = ContextMsg::new(parse_macro_input!(tokens as LitStr), r.clone());
    } else {
        // If the return type is the default return type () then skip processing
        return TokenStream::from(quote! {#input});
    }
    // Handle Return and ? by folding the ItemFn syntax tree with the ContextMsg object
    let mut output = message.fold_item_fn(input);
    // Wrap the context of the function to grab the fall through Result then add the context
    // onto the any errors with map_err
    let rettype = message.rettype.clone();
    let mut block = output.block.clone();
    if message.has_ok {
        block
            .stmts
            .insert(0, parse_quote! { type HbErrorContextType #gen = #rettype; });
    }
    let msg = message.m.clone();
    output.block = parse_quote! {
        {
            #[allow(unreachable_code)]
            let ret: #rettype = {
                #[warn(unreachable_code)]
                #block
            };
            #[allow(unreachable_code)]
            ret.map_err(|er| er.make_inner().msg(#msg))
        }
    };
    // Convert the SyntaxTree back into a TokenTree
    TokenStream::from(quote! {#output})
}

/// Struct to handle the folding of the ItemFn.
struct Converter {
    rettype: Box<Type>,
}

// The Fold trait is used to inject the error handling into the the source code.
// The Fold will change this function...
// #[convert_error]
// fn basic_exampleerror() -> Result<(), ExampleError> {
//     if io_error()? {
//         return example_error().map_err(|e| e.msg("msgs are great"));
//     }
//     example_error()
// }
//
// into...
// fn basic_exampleerror() -> Result<(), ExampleError> {
//     if hb_error::ConvertInto::Result<(), ExampleError>::convert(io_error())? {
//         return hb_error::ConvertInto::Result<(), ExampleError>::convert(example_error().map_err(|e| e.msg("msgs are great")));
//     }
//     example_error()
// }
impl Fold for Converter {
    fn fold_expr(&mut self, e: Expr) -> Expr {
        match e {
            Expr::Return(mut rexpr) => {
                match rexpr.expr {
                    Some(ex) => {
                        let rettype = &self.rettype;
                        rexpr.expr =
                            Some(parse_quote!(hb_error::ConvertInto::<#rettype>::convert(#ex)));
                    }
                    None => (),
                }
                fold::fold_expr(self, Expr::Return(rexpr))
            }
            Expr::Try(mut texpr) => {
                let ex = texpr.expr;
                let rettype = &self.rettype;
                texpr.expr = parse_quote!(hb_error::ConvertInto::<#rettype>::convert(#ex));
                Expr::Try(texpr)
            }
            _ => fold::fold_expr(self, e),
        }
    }
}

/// Converts Errors returned by the function into the correct type for the
/// function as well adding a context message provided.
/// This macro will change the following function...
/// ```
/// #[convert_error]
/// fn basic_exampleerror() -> Result<(), ExampleError> {
///     if io_error()? {
///         return example_error().map_err(|e| e.msg("msgs are great"));
///     }
///     example_error()
/// }
/// ```
///
/// into...
/// ```
/// fn basic_exampleerror() -> Result<(), ExampleError> {
///     #[allow(unreachable_code)]
///     let ret: Result<(), ExampleError> = {
///            #[warn(unreachable_code)]
///         if hb_error::ConvertInto::Result<(), ExampleError>::convert(io_error())? {
///             return hb_error::ConvertInto::Result<(), ExampleError>::convert(example_error());
///         }
///         example_error()
///     };
///     #[allow(unreachable_code)]
///     ret
/// }
/// ```
#[proc_macro_attribute]
pub fn convert_error(_args: TokenStream, input: TokenStream) -> TokenStream {
    // convert the input TokenStream into a ItemFn syntax object
    let input = parse_macro_input!(input as ItemFn);
    let mut message;
    // Extract the return type from the function signature
    if let ReturnType::Type(_, r) = &input.sig.output {
        // Read the args provided as a LitStr ie contents of the () after context in the attibute
        // Then create a ContextMsg object
        message = Converter { rettype: r.clone() };
    } else {
        // If the return type is the default return type () then skip processing
        return TokenStream::from(quote! {#input});
    }
    // Handle Return and ? by folding the ItemFn syntax tree with the ContextMsg object
    let output = message.fold_item_fn(input);
    // Convert the SyntaxTree back into a TokenTree
    TokenStream::from(quote! {#output})
}

/// This macro is used to generate all of the boiler plate code for error types so that they all
/// have the same format.
/// # Overview
/// This macro is applied to structs like this one.
/// ```
/// #[hberror]
/// struct ExampleError {
/// }
/// ```
/// This macro will modify the struct to add in the msg and inner_msgs fields as well as doing the impls for new, ErrorContext, Display and Debug.
/// This will generate the following code:
///
/// ```
///
/// pub struct ExampleError {
///     msg: String,
///     inner_msgs: Vec<String>,
/// }
///
/// impl ExampleError {
///     pub fn new() -> ExampleError {
///         ExampleError {
///             msg: default::Default(),
///             inner_msgs: default::Default(),
///         }
///     }
/// }
///
/// impl ErrorContext for ExampleError {
///     fn make_inner(mut self) -> ExampleError {
///         self.inner_msgs.push(self.msg);
///         self.msg = String::new();
///         self
///     }
///
///     fn msg<T: Into<String>>(mut self, msg: T) -> ExampleError {
///         self.msg = msg.into();
///         self
///     }
/// }
///
/// impl std::fmt::Display for ExampleError {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
///         write!(f,"{}{}", self.msg, self.inner_msgs.join("\n...because..."))
///     }
/// }
///
/// impl std::fmt::Debug for ExampleError {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
///         write!(f,"{}{}", self.msg, self.inner_msgs.join("\n...because..."))
///     }
/// }
/// ```
/// # Custom fields and messages
/// This macro also has the capability of dealing with custom fields and custom messages.
/// Using the Default attribute on these custom fields will tell the macro to use the val provided
/// in the new function rather than default::Default().
///
/// ```
/// #[hberror("{self.custom_field}:{self.msg}{self.inner_msgs.join(\"\n...due to...\")}")]
/// struct ExampleError {
///     #[Default(10)]
///     custom_field: i32,
/// }
/// ```
/// This becomes
/// ```
/// pub struct ExampleError {
///     msg: String,
///     inner_msgs: Vec<String>,
///     custom_field: i32
/// }
///
/// impl ExampleError {
///     pub fn new() -> ExampleError {
///         ExampleError {
///             msg: default::Default(),
///             inner_msgs: default::Default(),
///             custom_field: 10
///         }
///     }
/// }
///
/// impl ErrorContext for ExampleError {
///     fn make_inner(mut self) -> ExampleError {
///         self.inner_msgs.push(self.msg);
///         self.msg = String::new();
///         self
///     }
///
///     fn msg<T: Into<String>>(mut self, msg: T) -> ExampleError {
///         self.msg = msg.into();
///         self
///     }
/// }
///
/// impl std::fmt::Display for ExampleError {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
///         write!(f,"{}:{}{}", self.custom_field, self.msg, self.inner_msgs.join("\n...due to..."))
///     }
/// }
///
/// impl std::fmt::Debug for ExampleError {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
///         write!(f,"{}:{}{}", self.custom_field, self.msg, self.inner_msgs.join("\n...due to..."))
///     }
/// }
/// ```
/// # Easy Conversion from other errors
/// You can also define errors that you want to convert from and store as a source variable which
/// will be printed after message. The Source attribute tell the macro which fields to process as
/// the source. A enum will be created using the identity of the sturct with Source at the end
/// (eg ExampleErrorSource). This enum will have variants for each field marked with a source
/// attribute as well as a None value. The variants for the sources are created using the field
/// identity as the enum variant identity and contains the error type provided.
///
/// This means that the context or convert_error macros can be used on this error type without any
/// additional work.
/// ```
/// #[hberror]
/// struct ExampleError {
///     #[Source]
///     IOError: std::io::Error,
/// }
/// ```
/// This becomes:
/// ```
/// use std::default;
/// pub struct ExampleError {
///     msg: String,
///     inner_msgs: Vec<String>,
///     source: ExampleErrorSource,
/// }
///
/// impl ExampleError {
///     pub fn new() -> ExampleError {
///         ExampleError {
///             msg: default::Default(),
///             inner_msgs: default::Default(),
///             source: default::Default(),
///         }
///     }
///
///     pub fn source(mut self, s: ExampleErrorSource) -> ExampleError {
///         self.source = s;
///         self
///     }
/// }
///
/// impl ErrorContext for ExampleError {
///     fn make_inner(mut self) -> ExampleError {
///         self.inner_msgs.push(self.msg);
///         self.msg = String::new();
///         self
///     }
///
///     fn msg<T: Into<String>>(mut self, msg: T) -> ExampleError {
///         self.msg = msg.into();
///         self
///     }
/// }
///
/// impl std::fmt::Display for ExampleError {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
///         write!(f,"{}{}{}", self.msg, self.inner_msgs.join("\n...due to..."), self.source)
///     }
/// }
///
/// impl std::fmt::Debug for ExampleError {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
///         write!(f,"{}{}{}", self.msg, self.inner_msgs.join("\n...due to..."), self.source)
///     }
/// }
///
/// pub enum ExampleErrorSource {
///     None,
///     IOError(std::io::Error),
/// }
///
/// impl std::default::Default for ExampleErrorSource {
///     fn default() -> Self { ExampleErrorSource::None }
/// }
///
/// impl std::fmt::Display for ExampleErrorSource {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
///         match self {
///             ExampleErrorSource::None => Ok(()),
///             ExampleErrorSource::IOError(e) => write!("\n...Source Error...{}", e)
///         }
///     }
/// }
///
/// impl std::fmt::Debug for ExampleErrorSource {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
///         match self {
///             ExampleErrorSource::None => Ok(()),
///             ExampleErrorSource::IOError(e) => write!("\n...Source Error...{}", e)
///         }
///     }
/// }
///
/// ```
#[proc_macro_attribute]
pub fn hberror(args: TokenStream, input: TokenStream) -> TokenStream {
    // parse the input as an ItemStruct, it should panic if anything other than a struct is annotated with this macro
    let input = parse_macro_input!(input as ItemStruct);
    // create a copy which we can edit easily
    let mut output_struct = input.clone();

    // get some details from the struct
    // Struct Name
    let ident = input.ident;
    // Create the source enum's name from the structs name
    let ident_source = Ident::new(&format!("{}Source", ident), Span::call_site());
    // visibility of the struct - eg pub
    let vis = input.vis;

    // sort and process the provided fields
    let mut has_source_enum = false;
    let mut enum_variants = syn::punctuated::Punctuated::<Variant, Comma>::new();
    let mut new_fields = syn::punctuated::Punctuated::<FieldValue, Comma>::new();
    let mut enum_display_match = ExprMatch {
        attrs: vec![],
        match_token: Default::default(),
        expr: Box::new(parse_quote!(self)),
        brace_token: Default::default(),
        arms: vec![],
    };
    let mut source_from_impl_items: Vec<Item> = vec![];
    let mut custom_fields = vec![];
    match &input.fields {
        Fields::Named(namedfields) => {
            namedfields.named.iter().for_each(|f| {
                let mut handled = false;
                for a in &f.attrs {
                    if a.path.is_ident("Source") {
                        let mut cleaned_field = f.clone();
                        let mut cleaned_attrs : Vec<Attribute> = vec![];
                        f.attrs
                            .iter()
                            .filter(|a| !a.path.is_ident("Source"))
                            .for_each(|a| cleaned_attrs.push(a.clone()));
                        cleaned_field.attrs = cleaned_attrs;
                        let ty = f.ty.clone();
                        let f_ident = f.ident.clone().unwrap();
                        enum_variants.push(Variant {
                            ident: f.ident.clone().unwrap(),
                            attrs: vec![],
                            fields: Fields::Unnamed(parse_quote!((#ty))),
                            discriminant: None,
                        });
                        enum_display_match
                            .arms
                            .push(parse_quote!(#ident_source::#f_ident(e) => write!(f, "\n...source error {}...{}",stringify!(#f_ident), e)));
                        source_from_impl_items.push(parse_quote!(impl From<#ty> for #ident {
                                fn from(e: #ty) -> #ident {
                                    #ident::new().source(#ident_source::#f_ident(e))
                                }
                            }));
                        has_source_enum = true;
                        handled = true;
                        break;
                    } else if a.path.is_ident("Default") {
                        let mut cleaned_field = f.clone();
                        let mut cleaned_attrs : Vec<Attribute> = vec![];
                        f.attrs
                            .iter()
                            .filter(|a| !a.path.is_ident("Default"))
                            .for_each(|a| cleaned_attrs.push(a.clone()));
                        cleaned_field.attrs = cleaned_attrs;
                        custom_fields.push((cleaned_field, Some(a.tokens.clone())));
                        handled = true;
                        break;
                    }
                }
                if !handled {
                    custom_fields.push((f.clone(), None));
                }
            });
        }
        Fields::Unnamed(_) => (),
        Fields::Unit => (),
    };
    if has_source_enum {
        enum_variants.push(Variant {
            ident: parse_quote!(None),
            attrs: vec![],
            fields: Fields::Unit,
            discriminant: None,
        });
        enum_display_match
            .arms
            .push(parse_quote!(#ident_source::None => Ok(())))
    }
    new_fields.push(parse_quote!(msg: String::new()));
    new_fields.push(parse_quote!(inner_msgs: vec![]));
    let mut final_fields = Fields::Named(match has_source_enum {
        true => {
            new_fields.push(parse_quote!(source: #ident_source::None));
            parse_quote! {
                {
                    msg: String,
                    inner_msgs: Vec<String>,
                    source: #ident_source,
                }
            }
        }
        false => parse_quote! {
            {
                msg: String,
                inner_msgs: Vec<String>,
            }
        },
    });
    match &mut final_fields {
        Fields::Named(ref mut named_fields) => {
            for (f, toks) in custom_fields {
                let f_ident = f.ident.clone();
                named_fields.named.push(f);
                match toks {
                    Some(tok) => new_fields.push(parse_quote!(#f_ident: #tok)),
                    None => new_fields.push(parse_quote!(#f_ident: Default::default())),
                }
            }
        }
        _ => panic!("should not happen"),
    }
    let mut msg_args = syn::punctuated::Punctuated::<Expr, Comma>::new();
    msg_args.push(parse_quote!(f));
    match syn::parse::<LitStr>(args) {
        Err(_) => {
            if has_source_enum {
                msg_args.push(parse_quote!("{}{}{}"));
                msg_args.push(parse_quote!(self.msg));
                msg_args.push(parse_quote!(self.inner_msgs.join("\n...because...")));
                msg_args.push(parse_quote!(self.source));
            } else {
                msg_args.push(parse_quote!("{}{}"));
                msg_args.push(parse_quote!(self.msg));
                msg_args.push(parse_quote!(self.inner_msgs.join("\n...because...")));
            }
        }
        Ok(litstr) => {
            let str = litstr.value();
            let mut brace_contents: Vec<String> = vec![];
            let mut in_brace = false;
            let mut buf = String::new();
            let mut out_str = String::new();
            for c in str.chars() {
                if c == '{' {
                    in_brace = true;
                    out_str.push(c);
                } else if c == '}' {
                    if buf.len() > 0 {
                        brace_contents.push(buf);
                        buf = String::new();
                    }
                    in_brace = false;
                    out_str.push(c);
                } else if in_brace {
                    buf.push(c);
                } else {
                    out_str.push(c);
                }
            }

            for content in brace_contents {
                msg_args
                    .push(syn::parse_str::<Expr>(&content).expect(
                        format!("cannot convert {} into an expression.", content).as_str(),
                    ));
            }
            if has_source_enum {
                msg_args.push(parse_quote!(self.source));
                out_str.push_str("{}")
            }
            msg_args.insert(1, parse_quote!(#out_str));
        }
    }
    output_struct.fields = final_fields;

    //Build the output code
    //Parts that don't matter if there is any source enum
    let main_output = quote!(
                #output_struct

                impl ErrorContext for #ident {
                    fn make_inner(mut self) -> #ident {
                        self.inner_msgs.push(self.msg);
                        self.msg = String::new();
                        self
                    }

                    fn msg<T: Into<String>>(mut self, msg: T) -> #ident {
                        self.msg = msg.into();
                        self
                    }
                }

                impl std::fmt::Display for #ident {
                    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
                        write!(#msg_args)
                    }
                }

                impl std::fmt::Debug for #ident {
                    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
                        write!(#msg_args)
                    }
                }
    );

    // Add source enum stuff if there is one
    let final_output = match has_source_enum {
        true => {
            let mut out = quote!(
                #main_output

                impl #ident {
                    /// Create a new error with empty values.
                    #vis fn new() -> #ident {
                        #ident {
                            #new_fields
                        }
                    }

                    /// Set the source value of the error type with special enum. This function is
                    /// usually used by the From implementation between the source error type and
                    /// the final error type, where the source error is stored in the applicable
                    /// variant of the enum in the source field of the error.
                    #vis fn source(mut self, s: #ident_source) -> #ident {
                        self.source = s;
                        self
                    }
                }

                /// This enum represents all of the errors that can be a source for this Error.
                /// The trait From has been implemented between all of these Error types and the
                /// main error type where the source field is set to the applicable variant of this
                /// enum.
                #vis enum #ident_source {
                    #enum_variants
                }

                impl std::fmt::Display for #ident_source {
                    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
                        #enum_display_match
                    }
                }

                impl std::fmt::Debug for #ident_source {
                    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
                        #enum_display_match
                    }
                }

                impl std::default::Default for #ident_source {
                    fn default() -> Self { #ident_source::None }
                }
            );
            out.append_all(source_from_impl_items);
            out
        }
        false => {
            parse_quote!(
                #main_output

                impl #ident {
                    #vis fn new() -> #ident {
                        #ident {
                            #new_fields
                        }
                    }
                }

            )
        }
    };
    final_output.into()
}