-
Notifications
You must be signed in to change notification settings - Fork 61
/
lib.rs
2209 lines (1897 loc) · 69.4 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
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
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![recursion_limit = "128"] // https://github.com/rust-lang/rust/issues/62059
extern crate proc_macro;
use crate::parse::attributes_from_syn;
use proc_macro::TokenStream;
use quote::quote;
use std::collections::{BTreeSet, VecDeque};
use std::fmt;
mod parse;
mod shared;
// The snafu crate re-exports this and adds useful documentation.
#[proc_macro_derive(Snafu, attributes(snafu))]
pub fn snafu_derive(input: TokenStream) -> TokenStream {
let ast = syn::parse(input).expect("Could not parse type to derive Error for");
impl_snafu_macro(ast)
}
mod report;
#[proc_macro_attribute]
pub fn report(attr: TokenStream, item: TokenStream) -> TokenStream {
report::body(attr, item)
.unwrap_or_else(|e| e.to_compile_error())
.into()
}
type MultiSynResult<T> = std::result::Result<T, Vec<syn::Error>>;
/// Some arbitrary tokens we treat as a black box
type UserInput = Box<dyn quote::ToTokens>;
enum ModuleName {
Default,
Custom(syn::Ident),
}
enum SnafuInfo {
Enum(EnumInfo),
NamedStruct(NamedStructInfo),
TupleStruct(TupleStructInfo),
}
struct EnumInfo {
crate_root: UserInput,
name: syn::Ident,
generics: syn::Generics,
variants: Vec<FieldContainer>,
default_visibility: Option<UserInput>,
default_suffix: SuffixKind,
module: Option<ModuleName>,
}
/// A struct or enum variant, with named fields.
struct FieldContainer {
name: syn::Ident,
backtrace_field: Option<Field>,
implicit_fields: Vec<Field>,
selector_kind: ContextSelectorKind,
display_format: Option<Display>,
doc_comment: Option<DocComment>,
visibility: Option<UserInput>,
module: Option<ModuleName>,
provides: Vec<Provide>,
is_transparent: bool,
}
impl FieldContainer {
fn user_fields(&self) -> &[Field] {
self.selector_kind.user_fields()
}
fn provides(&self) -> &[Provide] {
&self.provides
}
}
struct Provide {
is_chain: bool,
is_opt: bool,
is_priority: bool,
is_ref: bool,
ty: syn::Type,
expr: syn::Expr,
}
enum SuffixKind {
Default,
None,
Some(syn::Ident),
}
impl SuffixKind {
fn resolve_with_default<'a>(&'a self, def: &'a Self) -> &'a Self {
use SuffixKind::*;
match self {
Default => def,
None => self,
Some(_) => self,
}
}
}
enum ContextSelectorKind {
Context {
suffix: SuffixKind,
source_field: Option<SourceField>,
user_fields: Vec<Field>,
},
Whatever {
source_field: Option<SourceField>,
message_field: Field,
},
NoContext {
source_field: SourceField,
},
}
impl ContextSelectorKind {
fn is_whatever(&self) -> bool {
matches!(self, ContextSelectorKind::Whatever { .. })
}
fn user_fields(&self) -> &[Field] {
match self {
ContextSelectorKind::Context { user_fields, .. } => user_fields,
ContextSelectorKind::Whatever { .. } => &[],
ContextSelectorKind::NoContext { .. } => &[],
}
}
fn source_field(&self) -> Option<&SourceField> {
match self {
ContextSelectorKind::Context { source_field, .. } => source_field.as_ref(),
ContextSelectorKind::Whatever { source_field, .. } => source_field.as_ref(),
ContextSelectorKind::NoContext { source_field } => Some(source_field),
}
}
fn message_field(&self) -> Option<&Field> {
match self {
ContextSelectorKind::Context { .. } => None,
ContextSelectorKind::Whatever { message_field, .. } => Some(message_field),
ContextSelectorKind::NoContext { .. } => None,
}
}
}
struct NamedStructInfo {
crate_root: UserInput,
field_container: FieldContainer,
generics: syn::Generics,
}
struct TupleStructInfo {
crate_root: UserInput,
name: syn::Ident,
generics: syn::Generics,
transformation: Transformation,
provides: Vec<Provide>,
}
#[derive(Clone)]
pub(crate) struct Field {
name: syn::Ident,
ty: syn::Type,
provide: bool,
original: syn::Field,
}
impl Field {
fn name(&self) -> &syn::Ident {
&self.name
}
}
struct SourceField {
name: syn::Ident,
transformation: Transformation,
backtrace_delegate: bool,
provide: bool,
}
impl SourceField {
fn name(&self) -> &syn::Ident {
&self.name
}
}
enum Transformation {
None {
ty: syn::Type,
},
Transform {
source_ty: syn::Type,
target_ty: syn::Type,
expr: syn::Expr,
},
}
impl Transformation {
fn source_ty(&self) -> &syn::Type {
match self {
Transformation::None { ty } => ty,
Transformation::Transform { source_ty, .. } => source_ty,
}
}
fn target_ty(&self) -> &syn::Type {
match self {
Transformation::None { ty } => ty,
Transformation::Transform { target_ty, .. } => target_ty,
}
}
fn transformation(&self) -> proc_macro2::TokenStream {
match self {
Transformation::None { .. } => quote! { |v| v },
Transformation::Transform { expr, .. } => quote! { #expr },
}
}
}
enum ProvideKind {
Flag(bool),
Expression(Provide),
}
/// SyntaxErrors is a convenience wrapper for a list of syntax errors discovered while parsing
/// something that derives Snafu. It makes it easier for developers to add and return syntax
/// errors while walking through the parse tree.
#[derive(Debug, Default)]
struct SyntaxErrors {
inner: Vec<syn::Error>,
}
impl SyntaxErrors {
/// Start a set of errors that all share the same location
fn scoped(&mut self, scope: ErrorLocation) -> SyntaxErrorsScoped<'_> {
SyntaxErrorsScoped {
errors: self,
scope,
}
}
/// Adds a new syntax error. The description will be used in the
/// compile error pointing to the tokens.
fn add(&mut self, tokens: impl quote::ToTokens, description: impl fmt::Display) {
self.inner
.push(syn::Error::new_spanned(tokens, description));
}
/// Adds the given list of errors.
fn extend(&mut self, errors: impl IntoIterator<Item = syn::Error>) {
self.inner.extend(errors);
}
#[allow(dead_code)]
/// Returns the number of errors that have been added.
fn len(&self) -> usize {
self.inner.len()
}
/// Consume the SyntaxErrors, returning Ok if there were no syntax errors added, or Err(list)
/// if there were syntax errors.
fn finish(self) -> MultiSynResult<()> {
if self.inner.is_empty() {
Ok(())
} else {
Err(self.inner)
}
}
/// Consume the SyntaxErrors and a Result, returning the success
/// value if neither have errors, otherwise combining the errors.
fn absorb<T>(mut self, res: MultiSynResult<T>) -> MultiSynResult<T> {
match res {
Ok(v) => self.finish().map(|()| v),
Err(e) => {
self.inner.extend(e);
Err(self.inner)
}
}
}
}
#[derive(Debug, Copy, Clone)]
enum ErrorLocation {
OnEnum,
OnVariant,
InVariant,
OnField,
OnNamedStruct,
InNamedStruct,
OnTupleStruct,
OnTupleStructField,
}
impl fmt::Display for ErrorLocation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use crate::ErrorLocation::*;
match self {
OnEnum => "on an enum".fmt(f),
OnVariant => "on an enum variant".fmt(f),
InVariant => "within an enum variant".fmt(f),
OnField => "on a field".fmt(f),
OnNamedStruct => "on a named struct".fmt(f),
InNamedStruct => "within a named struct".fmt(f),
OnTupleStruct => "on a tuple struct".fmt(f),
OnTupleStructField => "on a tuple struct field".fmt(f),
}
}
}
trait ErrorForLocation {
fn for_location(&self, location: ErrorLocation) -> String;
}
struct SyntaxErrorsScoped<'a> {
errors: &'a mut SyntaxErrors,
scope: ErrorLocation,
}
impl SyntaxErrorsScoped<'_> {
/// Adds a new syntax error. The description will be used in the
/// compile error pointing to the tokens.
fn add(&mut self, tokens: impl quote::ToTokens, description: impl ErrorForLocation) {
let description = description.for_location(self.scope);
self.errors.add(tokens, description)
}
}
/// Helper structure to handle cases where an attribute is
/// syntactically valid but semantically invalid.
#[derive(Debug)]
struct DoesNothing {
/// The name of the attribute that was misused.
attribute: &'static str,
}
impl ErrorForLocation for DoesNothing {
fn for_location(&self, _location: ErrorLocation) -> String {
format!("`{}` attribute has no effect", self.attribute)
}
}
/// Helper structure to handle cases where an attribute was used on an
/// element where it's not valid.
#[derive(Debug)]
struct OnlyValidOn {
/// The name of the attribute that was misused.
attribute: &'static str,
/// A description of where that attribute is valid.
valid_on: &'static str,
}
impl ErrorForLocation for OnlyValidOn {
fn for_location(&self, location: ErrorLocation) -> String {
format!(
"`{}` attribute is only valid on {}, not {}",
self.attribute, self.valid_on, location,
)
}
}
/// Helper structure to handle cases where a specific attribute value
/// was used on an field where it's not valid.
#[derive(Debug)]
struct WrongField {
/// The name of the attribute that was misused.
attribute: &'static str,
/// The name of the field where that attribute is valid.
valid_field: &'static str,
}
impl ErrorForLocation for WrongField {
fn for_location(&self, _location: ErrorLocation) -> String {
format!(
r#"`{}` attribute is only valid on a field named "{}", not on other fields"#,
self.attribute, self.valid_field,
)
}
}
/// Helper structure to handle cases where two incompatible attributes
/// were specified on the same element.
#[derive(Debug)]
struct IncompatibleAttributes(&'static [&'static str]);
impl ErrorForLocation for IncompatibleAttributes {
fn for_location(&self, location: ErrorLocation) -> String {
let attrs_string = self
.0
.iter()
.map(|attr| format!("`{}`", attr))
.collect::<Vec<_>>()
.join(", ");
format!(
"Incompatible attributes [{}] specified {}",
attrs_string, location,
)
}
}
/// Helper structure to handle cases where an attribute was
/// incorrectly used multiple times on the same element.
#[derive(Debug)]
struct DuplicateAttribute {
attribute: &'static str,
location: ErrorLocation,
}
impl fmt::Display for DuplicateAttribute {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Multiple `{}` attributes are not supported {}",
self.attribute, self.location,
)
}
}
/// AtMostOne is a helper to track attributes seen during parsing. If more than one item is added,
/// it's added to a list of DuplicateAttribute errors, using the given `name` and `location` as
/// descriptors.
///
/// When done parsing a structure, call `finish` to get first attribute found, if any, and the list
/// of errors, or call `finish_with_location` to get the attribute and the token tree where it was
/// found, which can be useful for error reporting.
#[derive(Debug)]
struct AtMostOne<T, U>
where
U: quote::ToTokens,
{
name: &'static str,
location: ErrorLocation,
// We store all the values we've seen to allow for `iter`, which helps the `AtMostOne` be
// useful for additional manual error checking.
values: VecDeque<(T, U)>,
errors: SyntaxErrors,
}
impl<T, U> AtMostOne<T, U>
where
U: quote::ToTokens + Clone,
{
/// Creates an AtMostOne to track an attribute with the given
/// `name` on the given `location` (often referencing a parent
/// element).
fn new(name: &'static str, location: ErrorLocation) -> Self {
Self {
name,
location,
values: VecDeque::new(),
errors: SyntaxErrors::default(),
}
}
/// Add an occurence of the attribute found at the given token tree `tokens`.
fn add(&mut self, item: T, tokens: U) {
if !self.values.is_empty() {
self.errors.add(
tokens.clone(),
DuplicateAttribute {
attribute: self.name,
location: self.location,
},
);
}
self.values.push_back((item, tokens));
}
#[allow(dead_code)]
/// Returns the number of elements that have been added.
fn len(&self) -> usize {
self.values.len()
}
/// Returns true if no elements have been added, otherwise false.
#[allow(dead_code)]
fn is_empty(&self) -> bool {
self.values.is_empty()
}
/// Returns an iterator over all values that have been added.
///
/// This can help with additional manual error checks beyond the duplication checks that
/// `AtMostOne` handles for you.
fn iter(&self) -> std::collections::vec_deque::Iter<(T, U)> {
self.values.iter()
}
/// Consumes the AtMostOne, returning the first item added, if any, and the list of errors
/// representing any items added beyond the first.
fn finish(self) -> (Option<T>, Vec<syn::Error>) {
let (value, errors) = self.finish_with_location();
(value.map(|(val, _location)| val), errors)
}
/// Like `finish` but also returns the location of the first item added. Useful when you have
/// to do additional, manual error checking on the first item added, and you'd like to report
/// an accurate location for it in case of errors.
fn finish_with_location(mut self) -> (Option<(T, U)>, Vec<syn::Error>) {
let errors = match self.errors.finish() {
Ok(()) => Vec::new(),
Err(vec) => vec,
};
(self.values.pop_front(), errors)
}
}
fn impl_snafu_macro(ty: syn::DeriveInput) -> TokenStream {
match parse_snafu_information(ty) {
Ok(info) => info.into(),
Err(e) => to_compile_errors(e).into(),
}
}
fn to_compile_errors(errors: Vec<syn::Error>) -> proc_macro2::TokenStream {
let compile_errors = errors.iter().map(syn::Error::to_compile_error);
quote! { #(#compile_errors)* }
}
fn parse_snafu_information(ty: syn::DeriveInput) -> MultiSynResult<SnafuInfo> {
use syn::spanned::Spanned;
use syn::Data;
let span = ty.span();
let syn::DeriveInput {
ident,
generics,
data,
attrs,
..
} = ty;
match data {
Data::Enum(enum_) => parse_snafu_enum(enum_, ident, generics, attrs).map(SnafuInfo::Enum),
Data::Struct(struct_) => parse_snafu_struct(struct_, ident, generics, attrs, span),
_ => Err(vec![syn::Error::new(
span,
"Can only derive `Snafu` for an enum or a newtype",
)]),
}
}
const ATTR_DISPLAY: OnlyValidOn = OnlyValidOn {
attribute: "display",
valid_on: "enum variants or structs with named fields",
};
const ATTR_SOURCE: OnlyValidOn = OnlyValidOn {
attribute: "source",
valid_on: "enum variant or struct fields with a name",
};
const ATTR_SOURCE_BOOL: OnlyValidOn = OnlyValidOn {
attribute: "source(bool)",
valid_on: "enum variant or struct fields with a name",
};
const ATTR_SOURCE_FALSE: WrongField = WrongField {
attribute: "source(false)",
valid_field: "source",
};
const ATTR_SOURCE_FROM: OnlyValidOn = OnlyValidOn {
attribute: "source(from)",
valid_on: "enum variant or struct fields with a name",
};
const ATTR_BACKTRACE: OnlyValidOn = OnlyValidOn {
attribute: "backtrace",
valid_on: "enum variant or struct fields with a name",
};
const ATTR_BACKTRACE_FALSE: WrongField = WrongField {
attribute: "backtrace(false)",
valid_field: "backtrace",
};
const ATTR_IMPLICIT: OnlyValidOn = OnlyValidOn {
attribute: "implicit",
valid_on: "enum variant or struct fields with a name",
};
const ATTR_IMPLICIT_FALSE: DoesNothing = DoesNothing {
attribute: "implicit(false)",
};
const ATTR_VISIBILITY: OnlyValidOn = OnlyValidOn {
attribute: "visibility",
valid_on: "an enum, enum variants, or a struct with named fields",
};
const ATTR_MODULE: OnlyValidOn = OnlyValidOn {
attribute: "module",
valid_on: "an enum or structs with named fields",
};
const ATTR_PROVIDE_FLAG: OnlyValidOn = OnlyValidOn {
attribute: "provide",
valid_on: "enum variant or struct fields with a name",
};
const ATTR_PROVIDE_FALSE: WrongField = WrongField {
attribute: "provide(false)",
valid_field: r#"source" or "backtrace"#,
};
const ATTR_PROVIDE_EXPRESSION: OnlyValidOn = OnlyValidOn {
attribute: "provide(type => expression)",
valid_on: "enum variants, structs with named fields, or tuple structs",
};
const ATTR_CONTEXT: OnlyValidOn = OnlyValidOn {
attribute: "context",
valid_on: "enum variants or structs with named fields",
};
const ATTR_CONTEXT_FLAG: OnlyValidOn = OnlyValidOn {
attribute: "context(bool)",
valid_on: "enum variants or structs with named fields",
};
const ATTR_WHATEVER: OnlyValidOn = OnlyValidOn {
attribute: "whatever",
valid_on: "enum variants or structs with named fields",
};
const ATTR_CRATE_ROOT: OnlyValidOn = OnlyValidOn {
attribute: "crate_root",
valid_on: "an enum or a struct",
};
const ATTR_TRANSPARENT: OnlyValidOn = OnlyValidOn {
attribute: "transparent",
valid_on: "enum variants or structs with named fields",
};
const ATTR_TRANSPARENT_FALSE: DoesNothing = DoesNothing {
attribute: "transparent(false)",
};
const SOURCE_BOOL_FROM_INCOMPATIBLE: IncompatibleAttributes =
IncompatibleAttributes(&["source(false)", "source(from)"]);
fn parse_snafu_enum(
enum_: syn::DataEnum,
name: syn::Ident,
generics: syn::Generics,
attrs: Vec<syn::Attribute>,
) -> MultiSynResult<EnumInfo> {
use syn::spanned::Spanned;
use syn::Fields;
let mut errors = SyntaxErrors::default();
let mut modules = AtMostOne::new("module", ErrorLocation::OnEnum);
let mut default_visibilities = AtMostOne::new("visibility", ErrorLocation::OnEnum);
let mut default_suffixes = AtMostOne::new("context(suffix)", ErrorLocation::OnEnum);
let mut crate_roots = AtMostOne::new("crate_root", ErrorLocation::OnEnum);
let mut enum_errors = errors.scoped(ErrorLocation::OnEnum);
for attr in attributes_from_syn(attrs)? {
use SnafuAttribute as Att;
match attr {
Att::Visibility(tokens, v) => default_visibilities.add(v, tokens),
Att::Display(tokens, ..) => enum_errors.add(tokens, ATTR_DISPLAY),
Att::Source(tokens, ss) => {
for s in ss {
match s {
Source::Flag(..) => enum_errors.add(tokens.clone(), ATTR_SOURCE_BOOL),
Source::From(..) => enum_errors.add(tokens.clone(), ATTR_SOURCE_FROM),
}
}
}
Att::CrateRoot(tokens, root) => crate_roots.add(root, tokens),
Att::Context(tokens, c) => match c {
Context::Suffix(s) => default_suffixes.add(s, tokens),
Context::Flag(_) => enum_errors.add(tokens, ATTR_CONTEXT_FLAG),
},
Att::Module(tokens, v) => modules.add(v, tokens),
Att::Provide(tokens, ProvideKind::Flag(..)) => {
enum_errors.add(tokens, ATTR_PROVIDE_FLAG)
}
Att::Provide(tokens, ProvideKind::Expression { .. }) => {
enum_errors.add(tokens, ATTR_PROVIDE_EXPRESSION)
}
Att::Backtrace(tokens, ..) => enum_errors.add(tokens, ATTR_BACKTRACE),
Att::Implicit(tokens, ..) => enum_errors.add(tokens, ATTR_IMPLICIT),
Att::Transparent(tokens, ..) => enum_errors.add(tokens, ATTR_TRANSPARENT),
Att::Whatever(tokens) => enum_errors.add(tokens, ATTR_WHATEVER),
Att::DocComment(..) => { /* Just a regular doc comment. */ }
}
}
let (module, errs) = modules.finish();
errors.extend(errs);
let (default_visibility, errs) = default_visibilities.finish();
errors.extend(errs);
let (maybe_default_suffix, errs) = default_suffixes.finish();
let default_suffix = maybe_default_suffix.unwrap_or(SuffixKind::Default);
errors.extend(errs);
let (maybe_crate_root, errs) = crate_roots.finish();
let crate_root = maybe_crate_root.unwrap_or_else(default_crate_root);
errors.extend(errs);
let variants: sponge::AllErrors<_, _> = enum_
.variants
.into_iter()
.map(|variant| {
let fields = match variant.fields {
Fields::Named(f) => f.named.into_iter().collect(),
Fields::Unnamed(_) => {
return Err(vec![syn::Error::new(
variant.fields.span(),
"Can only derive `Snafu` for enums with struct-like and unit enum variants",
)]);
}
Fields::Unit => vec![],
};
let name = variant.ident;
let span = name.span();
let attrs = attributes_from_syn(variant.attrs)?;
field_container(
name,
span,
attrs,
fields,
&mut errors,
ErrorLocation::OnVariant,
ErrorLocation::InVariant,
)
})
.collect();
let variants = errors.absorb(variants.into_result())?;
Ok(EnumInfo {
crate_root,
name,
generics,
variants,
default_visibility,
default_suffix,
module,
})
}
fn field_container(
name: syn::Ident,
variant_span: proc_macro2::Span,
attrs: Vec<SnafuAttribute>,
fields: Vec<syn::Field>,
errors: &mut SyntaxErrors,
outer_error_location: ErrorLocation,
inner_error_location: ErrorLocation,
) -> MultiSynResult<FieldContainer> {
use quote::ToTokens;
use syn::spanned::Spanned;
let mut outer_errors = errors.scoped(outer_error_location);
let mut modules = AtMostOne::new("module", outer_error_location);
let mut display_formats = AtMostOne::new("display", outer_error_location);
let mut visibilities = AtMostOne::new("visibility", outer_error_location);
let mut provides = Vec::new();
let mut contexts = AtMostOne::new("context", outer_error_location);
let mut whatevers = AtMostOne::new("whatever", outer_error_location);
let mut transparents = AtMostOne::new("transparent", outer_error_location);
let mut doc_comment = DocComment::default();
let mut reached_end_of_doc_comment = false;
for attr in attrs {
use SnafuAttribute as Att;
match attr {
Att::Module(tokens, n) => modules.add(n, tokens),
Att::Display(tokens, d) => display_formats.add(d, tokens),
Att::Visibility(tokens, v) => visibilities.add(v, tokens),
Att::Context(tokens, c) => contexts.add(c, tokens),
Att::Whatever(tokens) => whatevers.add((), tokens),
Att::Transparent(tokens, t) => {
if t {
transparents.add((), tokens)
} else {
outer_errors.add(tokens, ATTR_TRANSPARENT_FALSE)
}
}
Att::Source(tokens, ..) => outer_errors.add(tokens, ATTR_SOURCE),
Att::Backtrace(tokens, ..) => outer_errors.add(tokens, ATTR_BACKTRACE),
Att::Implicit(tokens, ..) => outer_errors.add(tokens, ATTR_IMPLICIT),
Att::CrateRoot(tokens, ..) => outer_errors.add(tokens, ATTR_CRATE_ROOT),
Att::Provide(tokens, ProvideKind::Flag(..)) => {
outer_errors.add(tokens, ATTR_PROVIDE_FLAG)
}
Att::Provide(_tts, ProvideKind::Expression(provide)) => {
// TODO: can we have improved error handling for obvious type duplicates?
provides.push(provide);
}
Att::DocComment(_tts, doc_comment_line) => {
// We join all the doc comment attributes with a space,
// but end once the summary of the doc comment is
// complete, which is indicated by an empty line.
if !reached_end_of_doc_comment {
let trimmed = doc_comment_line.trim();
if trimmed.is_empty() {
reached_end_of_doc_comment = true;
} else {
doc_comment.push_str(trimmed);
}
}
}
}
}
let mut user_fields = Vec::new();
let mut source_fields = AtMostOne::new("source", inner_error_location);
let mut backtrace_fields = AtMostOne::new("backtrace", inner_error_location);
let mut implicit_fields = Vec::new();
for syn_field in fields {
let original = syn_field.clone();
let span = syn_field.span();
let name = syn_field
.ident
.as_ref()
.ok_or_else(|| vec![syn::Error::new(span, "Must have a named field")])?;
// Check whether we have multiple source/backtrace attributes on this field.
// We can't just add to source_fields/backtrace_fields from inside the attribute
// loop because source and backtrace are connected and require a bit of special
// logic after the attribute loop. For example, we need to know whether there's a
// source transformation before we record a source field, but it might be on a
// later attribute. We use the data field of `source_attrs` to track any
// transformations in case it was a `source(from(...))`, but for backtraces we
// don't need any more data.
let mut source_attrs = AtMostOne::new("source", ErrorLocation::OnField);
let mut backtrace_attrs = AtMostOne::new("backtrace", ErrorLocation::OnField);
let mut implicit_attrs = AtMostOne::new("implicit", ErrorLocation::OnField);
let mut provide_attrs = AtMostOne::new("provide", ErrorLocation::OnField);
// Keep track of the negative markers so we can check for inconsistencies and
// exclude fields even if they have the "source" or "backtrace" name.
let mut source_opt_out = false;
let mut backtrace_opt_out = false;
let mut provide_opt_out = false;
let mut field_errors = errors.scoped(ErrorLocation::OnField);
for attr in attributes_from_syn(syn_field.attrs.clone())? {
use SnafuAttribute as Att;
match attr {
Att::Source(tokens, ss) => {
for s in ss {
match s {
Source::Flag(v) => {
// If we've seen a `source(from)` then there will be a
// `Some` value in `source_attrs`.
let seen_source_from = source_attrs
.iter()
.map(|(val, _location)| val)
.any(Option::is_some);
if !v && seen_source_from {
field_errors.add(tokens.clone(), SOURCE_BOOL_FROM_INCOMPATIBLE);
}
if v {
source_attrs.add(None, tokens.clone());
} else if is_implicit_source(name) {
source_opt_out = true;
} else {
field_errors.add(tokens.clone(), ATTR_SOURCE_FALSE);
}
}
Source::From(t, e) => {
if source_opt_out {
field_errors.add(tokens.clone(), SOURCE_BOOL_FROM_INCOMPATIBLE);
}
source_attrs.add(Some((t, e)), tokens.clone());
}
}
}
}
Att::Backtrace(tokens, v) => {
if v {
backtrace_attrs.add((), tokens);
} else if is_implicit_backtrace(name) {
backtrace_opt_out = true;
} else {
field_errors.add(tokens, ATTR_BACKTRACE_FALSE);
}
}
Att::Implicit(tokens, v) => {
if v {
implicit_attrs.add((), tokens);
} else {
field_errors.add(tokens, ATTR_IMPLICIT_FALSE);
}
}
Att::Module(tokens, ..) => field_errors.add(tokens, ATTR_MODULE),
Att::Provide(tokens, ProvideKind::Flag(v)) => {
if v {
provide_attrs.add((), tokens);
} else if is_implicit_provide(name) {
provide_opt_out = true;
} else {
field_errors.add(tokens, ATTR_PROVIDE_FALSE)
}
}
Att::Provide(tokens, ProvideKind::Expression { .. }) => {
field_errors.add(tokens, ATTR_PROVIDE_EXPRESSION)
}
Att::Visibility(tokens, ..) => field_errors.add(tokens, ATTR_VISIBILITY),
Att::Display(tokens, ..) => field_errors.add(tokens, ATTR_DISPLAY),
Att::Context(tokens, ..) => field_errors.add(tokens, ATTR_CONTEXT),
Att::Transparent(tokens, ..) => field_errors.add(tokens, ATTR_TRANSPARENT),
Att::Whatever(tokens) => field_errors.add(tokens, ATTR_WHATEVER),
Att::CrateRoot(tokens, ..) => field_errors.add(tokens, ATTR_CRATE_ROOT),
Att::DocComment(..) => { /* Just a regular doc comment. */ }
}
}
// Add errors for any duplicated attributes on this field.
let (source_attr, errs) = source_attrs.finish_with_location();
errors.extend(errs);
let (backtrace_attr, errs) = backtrace_attrs.finish_with_location();
errors.extend(errs);
let (implicit_attr, errs) = implicit_attrs.finish();
errors.extend(errs);
let (provide_attr, errs) = provide_attrs.finish();
errors.extend(errs);
let field = Field {
name: name.clone(),
ty: syn_field.ty.clone(),
provide: provide_attr.is_some() || (is_implicit_provide(name) && !provide_opt_out),
original,
};
let source_attr = source_attr.or_else(|| {
if is_implicit_source(&field.name) && !source_opt_out {
Some((None, syn_field.clone().into_token_stream()))
} else {
None
}
});
let backtrace_attr = backtrace_attr.or_else(|| {
if is_implicit_backtrace(&field.name) && !backtrace_opt_out {
Some(((), syn_field.clone().into_token_stream()))
} else {
None
}
});
let implicit_attr = implicit_attr.is_some();
if let Some((maybe_transformation, location)) = source_attr {
let Field {
name, ty, provide, ..
} = field;
let transformation = maybe_transformation
.map(|(source_ty, expr)| Transformation::Transform {
source_ty,
target_ty: ty.clone(),
expr,
})
.unwrap_or_else(|| Transformation::None { ty });
source_fields.add(
SourceField {
name,
transformation,
// Specifying `backtrace` on a source field is how you request
// delegation of the backtrace to the source error type.
backtrace_delegate: backtrace_attr.is_some(),
provide,
},
location,
);
} else if let Some((_, location)) = backtrace_attr {