-
-
Notifications
You must be signed in to change notification settings - Fork 803
/
Copy pathattr.rs
1882 lines (1739 loc) · 67.7 KB
/
attr.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
use crate::internals::name::{MultiName, Name};
use crate::internals::symbol::*;
use crate::internals::{ungroup, Ctxt};
use proc_macro2::{Spacing, Span, TokenStream, TokenTree};
use quote::ToTokens;
use std::borrow::Cow;
use std::collections::BTreeSet;
use std::iter::FromIterator;
use syn::meta::ParseNestedMeta;
use syn::parse::ParseStream;
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{parse_quote, token, Ident, Lifetime, Token};
// This module handles parsing of `#[serde(...)]` attributes. The entrypoints
// are `attr::Container::from_ast`, `attr::Variant::from_ast`, and
// `attr::Field::from_ast`. Each returns an instance of the corresponding
// struct. Note that none of them return a Result. Unrecognized, malformed, or
// duplicated attributes result in a span_err but otherwise are ignored. The
// user will see errors simultaneously for all bad attributes in the crate
// rather than just the first.
pub use crate::internals::case::RenameRule;
pub(crate) struct Attr<'c, T> {
cx: &'c Ctxt,
name: Symbol,
tokens: TokenStream,
value: Option<T>,
}
impl<'c, T> Attr<'c, T> {
fn none(cx: &'c Ctxt, name: Symbol) -> Self {
Attr {
cx,
name,
tokens: TokenStream::new(),
value: None,
}
}
fn set<A: ToTokens>(&mut self, obj: A, value: T) {
let tokens = obj.into_token_stream();
if self.value.is_some() {
let msg = format!("duplicate serde attribute `{}`", self.name);
self.cx.error_spanned_by(tokens, msg);
} else {
self.tokens = tokens;
self.value = Some(value);
}
}
fn set_opt<A: ToTokens>(&mut self, obj: A, value: Option<T>) {
if let Some(value) = value {
self.set(obj, value);
}
}
fn set_if_none(&mut self, value: T) {
if self.value.is_none() {
self.value = Some(value);
}
}
pub(crate) fn get(self) -> Option<T> {
self.value
}
fn get_with_tokens(self) -> Option<(TokenStream, T)> {
match self.value {
Some(v) => Some((self.tokens, v)),
None => None,
}
}
}
struct BoolAttr<'c>(Attr<'c, ()>);
impl<'c> BoolAttr<'c> {
fn none(cx: &'c Ctxt, name: Symbol) -> Self {
BoolAttr(Attr::none(cx, name))
}
fn set_true<A: ToTokens>(&mut self, obj: A) {
self.0.set(obj, ());
}
fn get(&self) -> bool {
self.0.value.is_some()
}
}
pub(crate) struct VecAttr<'c, T> {
cx: &'c Ctxt,
name: Symbol,
first_dup_tokens: TokenStream,
values: Vec<T>,
}
impl<'c, T> VecAttr<'c, T> {
fn none(cx: &'c Ctxt, name: Symbol) -> Self {
VecAttr {
cx,
name,
first_dup_tokens: TokenStream::new(),
values: Vec::new(),
}
}
fn insert<A: ToTokens>(&mut self, obj: A, value: T) {
if self.values.len() == 1 {
self.first_dup_tokens = obj.into_token_stream();
}
self.values.push(value);
}
fn at_most_one(mut self) -> Option<T> {
if self.values.len() > 1 {
let dup_token = self.first_dup_tokens;
let msg = format!("duplicate serde attribute `{}`", self.name);
self.cx.error_spanned_by(dup_token, msg);
None
} else {
self.values.pop()
}
}
pub(crate) fn get(self) -> Vec<T> {
self.values
}
}
fn unraw(ident: &Ident) -> Ident {
Ident::new(ident.to_string().trim_start_matches("r#"), ident.span())
}
#[derive(Copy, Clone)]
pub struct RenameAllRules {
pub serialize: RenameRule,
pub deserialize: RenameRule,
}
impl RenameAllRules {
/// Returns a new `RenameAllRules` with the individual rules of `self` and
/// `other_rules` joined by `RenameRules::or`.
pub fn or(self, other_rules: Self) -> Self {
Self {
serialize: self.serialize.or(other_rules.serialize),
deserialize: self.deserialize.or(other_rules.deserialize),
}
}
}
/// Represents struct or enum attribute information.
pub struct Container {
name: MultiName,
transparent: bool,
deny_unknown_fields: bool,
default: Default,
rename_all_rules: RenameAllRules,
rename_all_fields_rules: RenameAllRules,
ser_bound: Option<Vec<syn::WherePredicate>>,
de_bound: Option<Vec<syn::WherePredicate>>,
tag: TagType,
type_from: Option<syn::Type>,
type_try_from: Option<syn::Type>,
type_into: Option<syn::Type>,
remote: Option<syn::Path>,
identifier: Identifier,
serde_path: Option<syn::Path>,
is_packed: bool,
implied: Vec<(Name, Name)>,
/// Error message generated when type can't be deserialized
expecting: Option<String>,
non_exhaustive: bool,
}
/// Styles of representing an enum.
pub enum TagType {
/// The default.
///
/// ```json
/// {"variant1": {"key1": "value1", "key2": "value2"}}
/// ```
External,
/// `#[serde(tag = "type")]`
///
/// ```json
/// {"type": "variant1", "key1": "value1", "key2": "value2"}
/// ```
Internal { tag: String },
/// `#[serde(tag = "t", content = "c")]`
///
/// ```json
/// {"t": "variant1", "c": {"key1": "value1", "key2": "value2"}}
/// ```
Adjacent { tag: String, content: String },
/// `#[serde(untagged)]`
///
/// ```json
/// {"key1": "value1", "key2": "value2"}
/// ```
None,
}
/// Whether this enum represents the fields of a struct or the variants of an
/// enum.
#[derive(Copy, Clone)]
pub enum Identifier {
/// It does not.
No,
/// This enum represents the fields of a struct. All of the variants must be
/// unit variants, except possibly one which is annotated with
/// `#[serde(other)]` and is a newtype variant.
Field,
/// This enum represents the variants of an enum. All of the variants must
/// be unit variants.
Variant,
}
impl Identifier {
#[cfg(feature = "deserialize_in_place")]
pub fn is_some(self) -> bool {
match self {
Identifier::No => false,
Identifier::Field | Identifier::Variant => true,
}
}
}
impl Container {
/// Extract out the `#[serde(...)]` attributes from an item.
pub fn from_ast(cx: &Ctxt, item: &syn::DeriveInput) -> Self {
let mut ser_name = Attr::none(cx, RENAME);
let mut de_name = Attr::none(cx, RENAME);
let mut transparent = BoolAttr::none(cx, TRANSPARENT);
let mut deny_unknown_fields = BoolAttr::none(cx, DENY_UNKNOWN_FIELDS);
let mut default = Attr::none(cx, DEFAULT);
let mut rename_all_ser_rule = Attr::none(cx, RENAME_ALL);
let mut rename_all_de_rule = Attr::none(cx, RENAME_ALL);
let mut rename_all_fields_ser_rule = Attr::none(cx, RENAME_ALL_FIELDS);
let mut rename_all_fields_de_rule = Attr::none(cx, RENAME_ALL_FIELDS);
let mut ser_bound = Attr::none(cx, BOUND);
let mut de_bound = Attr::none(cx, BOUND);
let mut untagged = BoolAttr::none(cx, UNTAGGED);
let mut internal_tag = Attr::none(cx, TAG);
let mut content = Attr::none(cx, CONTENT);
let mut type_from = Attr::none(cx, FROM);
let mut type_try_from = Attr::none(cx, TRY_FROM);
let mut type_into = Attr::none(cx, INTO);
let mut remote = Attr::none(cx, REMOTE);
let mut field_identifier = BoolAttr::none(cx, FIELD_IDENTIFIER);
let mut variant_identifier = BoolAttr::none(cx, VARIANT_IDENTIFIER);
let mut serde_path = Attr::none(cx, CRATE);
let mut expecting = Attr::none(cx, EXPECTING);
let mut non_exhaustive = false;
let mut implied = VecAttr::none(cx, IMPLIED);
for attr in &item.attrs {
if attr.path() != SERDE {
non_exhaustive |=
matches!(&attr.meta, syn::Meta::Path(path) if path == NON_EXHAUSTIVE);
continue;
}
if let syn::Meta::List(meta) = &attr.meta {
if meta.tokens.is_empty() {
continue;
}
}
if let Err(err) = attr.parse_nested_meta(|meta| {
if meta.path == RENAME {
// #[serde(rename = "foo")]
// #[serde(rename(serialize = "foo", deserialize = "bar"))]
let (ser, de) = get_renames(cx, RENAME, &meta)?;
ser_name.set_opt(&meta.path, ser.as_ref().map(Name::from));
de_name.set_opt(&meta.path, de.as_ref().map(Name::from));
} else if meta.path == RENAME_ALL {
// #[serde(rename_all = "foo")]
// #[serde(rename_all(serialize = "foo", deserialize = "bar"))]
let one_name = meta.input.peek(Token![=]);
let (ser, de) = get_renames(cx, RENAME_ALL, &meta)?;
if let Some(ser) = ser {
match RenameRule::from_str(&ser.value()) {
Ok(rename_rule) => rename_all_ser_rule.set(&meta.path, rename_rule),
Err(err) => cx.error_spanned_by(ser, err),
}
}
if let Some(de) = de {
match RenameRule::from_str(&de.value()) {
Ok(rename_rule) => rename_all_de_rule.set(&meta.path, rename_rule),
Err(err) => {
if !one_name {
cx.error_spanned_by(de, err);
}
}
}
}
} else if meta.path == RENAME_ALL_FIELDS {
// #[serde(rename_all_fields = "foo")]
// #[serde(rename_all_fields(serialize = "foo", deserialize = "bar"))]
let one_name = meta.input.peek(Token![=]);
let (ser, de) = get_renames(cx, RENAME_ALL_FIELDS, &meta)?;
match item.data {
syn::Data::Enum(_) => {
if let Some(ser) = ser {
match RenameRule::from_str(&ser.value()) {
Ok(rename_rule) => {
rename_all_fields_ser_rule.set(&meta.path, rename_rule);
}
Err(err) => cx.error_spanned_by(ser, err),
}
}
if let Some(de) = de {
match RenameRule::from_str(&de.value()) {
Ok(rename_rule) => {
rename_all_fields_de_rule.set(&meta.path, rename_rule);
}
Err(err) => {
if !one_name {
cx.error_spanned_by(de, err);
}
}
}
}
}
syn::Data::Struct(_) => {
let msg = "#[serde(rename_all_fields)] can only be used on enums";
cx.syn_error(meta.error(msg));
}
syn::Data::Union(_) => {
let msg = "#[serde(rename_all_fields)] can only be used on enums";
cx.syn_error(meta.error(msg));
}
}
} else if meta.path == TRANSPARENT {
// #[serde(transparent)]
transparent.set_true(meta.path);
} else if meta.path == DENY_UNKNOWN_FIELDS {
// #[serde(deny_unknown_fields)]
deny_unknown_fields.set_true(meta.path);
} else if meta.path == DEFAULT {
if meta.input.peek(Token![=]) {
// #[serde(default = "...")]
if let Some(path) = parse_lit_into_expr_path(cx, DEFAULT, &meta)? {
match &item.data {
syn::Data::Struct(syn::DataStruct { fields, .. }) => match fields {
syn::Fields::Named(_) | syn::Fields::Unnamed(_) => {
default.set(&meta.path, Default::Path(path));
}
syn::Fields::Unit => {
let msg = "#[serde(default = \"...\")] can only be used on structs that have fields";
cx.syn_error(meta.error(msg));
}
},
syn::Data::Enum(_) => {
let msg = "#[serde(default = \"...\")] can only be used on structs";
cx.syn_error(meta.error(msg));
}
syn::Data::Union(_) => {
let msg = "#[serde(default = \"...\")] can only be used on structs";
cx.syn_error(meta.error(msg));
}
}
}
} else {
// #[serde(default)]
match &item.data {
syn::Data::Struct(syn::DataStruct { fields, .. }) => match fields {
syn::Fields::Named(_) | syn::Fields::Unnamed(_) => {
default.set(meta.path, Default::Default);
}
syn::Fields::Unit => {
let msg = "#[serde(default)] can only be used on structs that have fields";
cx.error_spanned_by(fields, msg);
}
},
syn::Data::Enum(_) => {
let msg = "#[serde(default)] can only be used on structs";
cx.syn_error(meta.error(msg));
}
syn::Data::Union(_) => {
let msg = "#[serde(default)] can only be used on structs";
cx.syn_error(meta.error(msg));
}
}
}
} else if meta.path == BOUND {
// #[serde(bound = "T: SomeBound")]
// #[serde(bound(serialize = "...", deserialize = "..."))]
let (ser, de) = get_where_predicates(cx, &meta)?;
ser_bound.set_opt(&meta.path, ser);
de_bound.set_opt(&meta.path, de);
} else if meta.path == UNTAGGED {
// #[serde(untagged)]
match item.data {
syn::Data::Enum(_) => {
untagged.set_true(&meta.path);
}
syn::Data::Struct(_) => {
let msg = "#[serde(untagged)] can only be used on enums";
cx.syn_error(meta.error(msg));
}
syn::Data::Union(_) => {
let msg = "#[serde(untagged)] can only be used on enums";
cx.syn_error(meta.error(msg));
}
}
} else if meta.path == TAG {
// #[serde(tag = "type")]
if let Some(s) = get_lit_str(cx, TAG, &meta)? {
match &item.data {
syn::Data::Enum(_) => {
internal_tag.set(&meta.path, s.value());
}
syn::Data::Struct(syn::DataStruct { fields, .. }) => match fields {
syn::Fields::Named(_) => {
internal_tag.set(&meta.path, s.value());
}
syn::Fields::Unnamed(_) | syn::Fields::Unit => {
let msg = "#[serde(tag = \"...\")] can only be used on enums and structs with named fields";
cx.syn_error(meta.error(msg));
}
},
syn::Data::Union(_) => {
let msg = "#[serde(tag = \"...\")] can only be used on enums and structs with named fields";
cx.syn_error(meta.error(msg));
}
}
}
} else if meta.path == CONTENT {
// #[serde(content = "c")]
if let Some(s) = get_lit_str(cx, CONTENT, &meta)? {
match &item.data {
syn::Data::Enum(_) => {
content.set(&meta.path, s.value());
}
syn::Data::Struct(_) => {
let msg = "#[serde(content = \"...\")] can only be used on enums";
cx.syn_error(meta.error(msg));
}
syn::Data::Union(_) => {
let msg = "#[serde(content = \"...\")] can only be used on enums";
cx.syn_error(meta.error(msg));
}
}
}
} else if meta.path == FROM {
// #[serde(from = "Type")]
if let Some(from_ty) = parse_lit_into_ty(cx, FROM, &meta)? {
type_from.set_opt(&meta.path, Some(from_ty));
}
} else if meta.path == TRY_FROM {
// #[serde(try_from = "Type")]
if let Some(try_from_ty) = parse_lit_into_ty(cx, TRY_FROM, &meta)? {
type_try_from.set_opt(&meta.path, Some(try_from_ty));
}
} else if meta.path == INTO {
// #[serde(into = "Type")]
if let Some(into_ty) = parse_lit_into_ty(cx, INTO, &meta)? {
type_into.set_opt(&meta.path, Some(into_ty));
}
} else if meta.path == REMOTE {
// #[serde(remote = "...")]
if let Some(path) = parse_lit_into_path(cx, REMOTE, &meta)? {
if is_primitive_path(&path, "Self") {
remote.set(&meta.path, item.ident.clone().into());
} else {
remote.set(&meta.path, path);
}
}
} else if meta.path == FIELD_IDENTIFIER {
// #[serde(field_identifier)]
field_identifier.set_true(&meta.path);
} else if meta.path == VARIANT_IDENTIFIER {
// #[serde(variant_identifier)]
variant_identifier.set_true(&meta.path);
} else if meta.path == CRATE {
// #[serde(crate = "foo")]
if let Some(path) = parse_lit_into_path(cx, CRATE, &meta)? {
serde_path.set(&meta.path, path);
}
} else if meta.path == EXPECTING {
// #[serde(expecting = "a message")]
if let Some(s) = get_lit_str(cx, EXPECTING, &meta)? {
expecting.set(&meta.path, s.value());
}
} else if meta.path == IMPLIED {
// #[serde(implied(key = "key", value = "value")]
if let Some((key, value)) = parse_key_value_names(cx,IMPLIED,&meta)? {
implied.insert(&meta.path, (key, value));
}
} else {
let path = meta.path.to_token_stream().to_string().replace(' ', "");
return Err(
meta.error(format_args!("unknown serde container attribute `{}`", path))
);
}
Ok(())
}) {
cx.syn_error(err);
}
}
let mut is_packed = false;
for attr in &item.attrs {
if attr.path() == REPR {
let _ = attr.parse_args_with(|input: ParseStream| {
while let Some(token) = input.parse()? {
if let TokenTree::Ident(ident) = token {
is_packed |= ident == "packed";
}
}
Ok(())
});
}
}
Container {
name: MultiName::from_attrs(Name::from(&unraw(&item.ident)), ser_name, de_name, None),
transparent: transparent.get(),
deny_unknown_fields: deny_unknown_fields.get(),
default: default.get().unwrap_or(Default::None),
rename_all_rules: RenameAllRules {
serialize: rename_all_ser_rule.get().unwrap_or(RenameRule::None),
deserialize: rename_all_de_rule.get().unwrap_or(RenameRule::None),
},
rename_all_fields_rules: RenameAllRules {
serialize: rename_all_fields_ser_rule.get().unwrap_or(RenameRule::None),
deserialize: rename_all_fields_de_rule.get().unwrap_or(RenameRule::None),
},
ser_bound: ser_bound.get(),
de_bound: de_bound.get(),
tag: decide_tag(cx, item, untagged, internal_tag, content),
type_from: type_from.get(),
type_try_from: type_try_from.get(),
type_into: type_into.get(),
remote: remote.get(),
identifier: decide_identifier(cx, item, field_identifier, variant_identifier),
serde_path: serde_path.get(),
is_packed,
implied: implied.get(),
expecting: expecting.get(),
non_exhaustive,
}
}
pub fn name(&self) -> &MultiName {
&self.name
}
pub fn rename_all_rules(&self) -> RenameAllRules {
self.rename_all_rules
}
pub fn rename_all_fields_rules(&self) -> RenameAllRules {
self.rename_all_fields_rules
}
pub fn transparent(&self) -> bool {
self.transparent
}
pub fn deny_unknown_fields(&self) -> bool {
self.deny_unknown_fields
}
pub fn default(&self) -> &Default {
&self.default
}
pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> {
self.ser_bound.as_ref().map(|vec| &vec[..])
}
pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> {
self.de_bound.as_ref().map(|vec| &vec[..])
}
pub fn tag(&self) -> &TagType {
&self.tag
}
pub fn type_from(&self) -> Option<&syn::Type> {
self.type_from.as_ref()
}
pub fn type_try_from(&self) -> Option<&syn::Type> {
self.type_try_from.as_ref()
}
pub fn type_into(&self) -> Option<&syn::Type> {
self.type_into.as_ref()
}
pub fn remote(&self) -> Option<&syn::Path> {
self.remote.as_ref()
}
pub fn is_packed(&self) -> bool {
self.is_packed
}
pub fn implied(&self) -> &[(Name, Name)] {
&self.implied
}
pub fn identifier(&self) -> Identifier {
self.identifier
}
pub fn custom_serde_path(&self) -> Option<&syn::Path> {
self.serde_path.as_ref()
}
pub fn serde_path(&self) -> Cow<syn::Path> {
self.custom_serde_path()
.map_or_else(|| Cow::Owned(parse_quote!(_serde)), Cow::Borrowed)
}
/// Error message generated when type can't be deserialized.
/// If `None`, default message will be used
pub fn expecting(&self) -> Option<&str> {
self.expecting.as_ref().map(String::as_ref)
}
pub fn non_exhaustive(&self) -> bool {
self.non_exhaustive
}
}
fn decide_tag(
cx: &Ctxt,
item: &syn::DeriveInput,
untagged: BoolAttr,
internal_tag: Attr<String>,
content: Attr<String>,
) -> TagType {
match (
untagged.0.get_with_tokens(),
internal_tag.get_with_tokens(),
content.get_with_tokens(),
) {
(None, None, None) => TagType::External,
(Some(_), None, None) => TagType::None,
(None, Some((_, tag)), None) => {
// Check that there are no tuple variants.
if let syn::Data::Enum(data) = &item.data {
for variant in &data.variants {
match &variant.fields {
syn::Fields::Named(_) | syn::Fields::Unit => {}
syn::Fields::Unnamed(fields) => {
if fields.unnamed.len() != 1 {
let msg =
"#[serde(tag = \"...\")] cannot be used with tuple variants";
cx.error_spanned_by(variant, msg);
break;
}
}
}
}
}
TagType::Internal { tag }
}
(Some((untagged_tokens, ())), Some((tag_tokens, _)), None) => {
let msg = "enum cannot be both untagged and internally tagged";
cx.error_spanned_by(untagged_tokens, msg);
cx.error_spanned_by(tag_tokens, msg);
TagType::External // doesn't matter, will error
}
(None, None, Some((content_tokens, _))) => {
let msg = "#[serde(tag = \"...\", content = \"...\")] must be used together";
cx.error_spanned_by(content_tokens, msg);
TagType::External
}
(Some((untagged_tokens, ())), None, Some((content_tokens, _))) => {
let msg = "untagged enum cannot have #[serde(content = \"...\")]";
cx.error_spanned_by(untagged_tokens, msg);
cx.error_spanned_by(content_tokens, msg);
TagType::External
}
(None, Some((_, tag)), Some((_, content))) => TagType::Adjacent { tag, content },
(Some((untagged_tokens, ())), Some((tag_tokens, _)), Some((content_tokens, _))) => {
let msg = "untagged enum cannot have #[serde(tag = \"...\", content = \"...\")]";
cx.error_spanned_by(untagged_tokens, msg);
cx.error_spanned_by(tag_tokens, msg);
cx.error_spanned_by(content_tokens, msg);
TagType::External
}
}
}
fn decide_identifier(
cx: &Ctxt,
item: &syn::DeriveInput,
field_identifier: BoolAttr,
variant_identifier: BoolAttr,
) -> Identifier {
match (
&item.data,
field_identifier.0.get_with_tokens(),
variant_identifier.0.get_with_tokens(),
) {
(_, None, None) => Identifier::No,
(_, Some((field_identifier_tokens, ())), Some((variant_identifier_tokens, ()))) => {
let msg =
"#[serde(field_identifier)] and #[serde(variant_identifier)] cannot both be set";
cx.error_spanned_by(field_identifier_tokens, msg);
cx.error_spanned_by(variant_identifier_tokens, msg);
Identifier::No
}
(syn::Data::Enum(_), Some(_), None) => Identifier::Field,
(syn::Data::Enum(_), None, Some(_)) => Identifier::Variant,
(syn::Data::Struct(syn::DataStruct { struct_token, .. }), Some(_), None) => {
let msg = "#[serde(field_identifier)] can only be used on an enum";
cx.error_spanned_by(struct_token, msg);
Identifier::No
}
(syn::Data::Union(syn::DataUnion { union_token, .. }), Some(_), None) => {
let msg = "#[serde(field_identifier)] can only be used on an enum";
cx.error_spanned_by(union_token, msg);
Identifier::No
}
(syn::Data::Struct(syn::DataStruct { struct_token, .. }), None, Some(_)) => {
let msg = "#[serde(variant_identifier)] can only be used on an enum";
cx.error_spanned_by(struct_token, msg);
Identifier::No
}
(syn::Data::Union(syn::DataUnion { union_token, .. }), None, Some(_)) => {
let msg = "#[serde(variant_identifier)] can only be used on an enum";
cx.error_spanned_by(union_token, msg);
Identifier::No
}
}
}
/// Represents variant attribute information
pub struct Variant {
name: MultiName,
rename_all_rules: RenameAllRules,
ser_bound: Option<Vec<syn::WherePredicate>>,
de_bound: Option<Vec<syn::WherePredicate>>,
skip_deserializing: bool,
skip_serializing: bool,
other: bool,
serialize_with: Option<syn::ExprPath>,
deserialize_with: Option<syn::ExprPath>,
borrow: Option<BorrowAttribute>,
untagged: bool,
}
struct BorrowAttribute {
path: syn::Path,
lifetimes: Option<BTreeSet<syn::Lifetime>>,
}
impl Variant {
pub fn from_ast(cx: &Ctxt, variant: &syn::Variant) -> Self {
let mut ser_name = Attr::none(cx, RENAME);
let mut de_name = Attr::none(cx, RENAME);
let mut de_aliases = VecAttr::none(cx, RENAME);
let mut skip_deserializing = BoolAttr::none(cx, SKIP_DESERIALIZING);
let mut skip_serializing = BoolAttr::none(cx, SKIP_SERIALIZING);
let mut rename_all_ser_rule = Attr::none(cx, RENAME_ALL);
let mut rename_all_de_rule = Attr::none(cx, RENAME_ALL);
let mut ser_bound = Attr::none(cx, BOUND);
let mut de_bound = Attr::none(cx, BOUND);
let mut other = BoolAttr::none(cx, OTHER);
let mut serialize_with = Attr::none(cx, SERIALIZE_WITH);
let mut deserialize_with = Attr::none(cx, DESERIALIZE_WITH);
let mut borrow = Attr::none(cx, BORROW);
let mut untagged = BoolAttr::none(cx, UNTAGGED);
for attr in &variant.attrs {
if attr.path() != SERDE {
continue;
}
if let syn::Meta::List(meta) = &attr.meta {
if meta.tokens.is_empty() {
continue;
}
}
if let Err(err) = attr.parse_nested_meta(|meta| {
if meta.path == RENAME {
// #[serde(rename = "foo")]
// #[serde(rename(serialize = "foo", deserialize = "bar"))]
let (ser, de) = get_multiple_renames(cx, &meta)?;
ser_name.set_opt(&meta.path, ser.as_ref().map(Name::from));
for de_value in de {
de_name.set_if_none(Name::from(&de_value));
de_aliases.insert(&meta.path, Name::from(&de_value));
}
} else if meta.path == ALIAS {
// #[serde(alias = "foo")]
if let Some(s) = get_lit_str(cx, ALIAS, &meta)? {
de_aliases.insert(&meta.path, Name::from(&s));
}
} else if meta.path == RENAME_ALL {
// #[serde(rename_all = "foo")]
// #[serde(rename_all(serialize = "foo", deserialize = "bar"))]
let one_name = meta.input.peek(Token![=]);
let (ser, de) = get_renames(cx, RENAME_ALL, &meta)?;
if let Some(ser) = ser {
match RenameRule::from_str(&ser.value()) {
Ok(rename_rule) => rename_all_ser_rule.set(&meta.path, rename_rule),
Err(err) => cx.error_spanned_by(ser, err),
}
}
if let Some(de) = de {
match RenameRule::from_str(&de.value()) {
Ok(rename_rule) => rename_all_de_rule.set(&meta.path, rename_rule),
Err(err) => {
if !one_name {
cx.error_spanned_by(de, err);
}
}
}
}
} else if meta.path == SKIP {
// #[serde(skip)]
skip_serializing.set_true(&meta.path);
skip_deserializing.set_true(&meta.path);
} else if meta.path == SKIP_DESERIALIZING {
// #[serde(skip_deserializing)]
skip_deserializing.set_true(&meta.path);
} else if meta.path == SKIP_SERIALIZING {
// #[serde(skip_serializing)]
skip_serializing.set_true(&meta.path);
} else if meta.path == OTHER {
// #[serde(other)]
other.set_true(&meta.path);
} else if meta.path == BOUND {
// #[serde(bound = "T: SomeBound")]
// #[serde(bound(serialize = "...", deserialize = "..."))]
let (ser, de) = get_where_predicates(cx, &meta)?;
ser_bound.set_opt(&meta.path, ser);
de_bound.set_opt(&meta.path, de);
} else if meta.path == WITH {
// #[serde(with = "...")]
if let Some(path) = parse_lit_into_expr_path(cx, WITH, &meta)? {
let mut ser_path = path.clone();
ser_path
.path
.segments
.push(Ident::new("serialize", ser_path.span()).into());
serialize_with.set(&meta.path, ser_path);
let mut de_path = path;
de_path
.path
.segments
.push(Ident::new("deserialize", de_path.span()).into());
deserialize_with.set(&meta.path, de_path);
}
} else if meta.path == SERIALIZE_WITH {
// #[serde(serialize_with = "...")]
if let Some(path) = parse_lit_into_expr_path(cx, SERIALIZE_WITH, &meta)? {
serialize_with.set(&meta.path, path);
}
} else if meta.path == DESERIALIZE_WITH {
// #[serde(deserialize_with = "...")]
if let Some(path) = parse_lit_into_expr_path(cx, DESERIALIZE_WITH, &meta)? {
deserialize_with.set(&meta.path, path);
}
} else if meta.path == BORROW {
let borrow_attribute = if meta.input.peek(Token![=]) {
// #[serde(borrow = "'a + 'b")]
let lifetimes = parse_lit_into_lifetimes(cx, &meta)?;
BorrowAttribute {
path: meta.path.clone(),
lifetimes: Some(lifetimes),
}
} else {
// #[serde(borrow)]
BorrowAttribute {
path: meta.path.clone(),
lifetimes: None,
}
};
match &variant.fields {
syn::Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
borrow.set(&meta.path, borrow_attribute);
}
_ => {
let msg = "#[serde(borrow)] may only be used on newtype variants";
cx.error_spanned_by(variant, msg);
}
}
} else if meta.path == UNTAGGED {
untagged.set_true(&meta.path);
} else {
let path = meta.path.to_token_stream().to_string().replace(' ', "");
return Err(
meta.error(format_args!("unknown serde variant attribute `{}`", path))
);
}
Ok(())
}) {
cx.syn_error(err);
}
}
Variant {
name: MultiName::from_attrs(
Name::from(&unraw(&variant.ident)),
ser_name,
de_name,
Some(de_aliases),
),
rename_all_rules: RenameAllRules {
serialize: rename_all_ser_rule.get().unwrap_or(RenameRule::None),
deserialize: rename_all_de_rule.get().unwrap_or(RenameRule::None),
},
ser_bound: ser_bound.get(),
de_bound: de_bound.get(),
skip_deserializing: skip_deserializing.get(),
skip_serializing: skip_serializing.get(),
other: other.get(),
serialize_with: serialize_with.get(),
deserialize_with: deserialize_with.get(),
borrow: borrow.get(),
untagged: untagged.get(),
}
}
pub fn name(&self) -> &MultiName {
&self.name
}
pub fn aliases(&self) -> &BTreeSet<Name> {
self.name.deserialize_aliases()
}
pub fn rename_by_rules(&mut self, rules: RenameAllRules) {
if !self.name.serialize_renamed {
self.name.serialize.value =
rules.serialize.apply_to_variant(&self.name.serialize.value);
}
if !self.name.deserialize_renamed {
self.name.deserialize.value = rules
.deserialize
.apply_to_variant(&self.name.deserialize.value);
}
self.name
.deserialize_aliases
.insert(self.name.deserialize.clone());
}
pub fn rename_all_rules(&self) -> RenameAllRules {
self.rename_all_rules
}
pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> {
self.ser_bound.as_ref().map(|vec| &vec[..])
}
pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> {
self.de_bound.as_ref().map(|vec| &vec[..])
}
pub fn skip_deserializing(&self) -> bool {
self.skip_deserializing
}
pub fn skip_serializing(&self) -> bool {
self.skip_serializing
}
pub fn other(&self) -> bool {
self.other
}
pub fn serialize_with(&self) -> Option<&syn::ExprPath> {
self.serialize_with.as_ref()
}
pub fn deserialize_with(&self) -> Option<&syn::ExprPath> {
self.deserialize_with.as_ref()
}
pub fn untagged(&self) -> bool {
self.untagged
}
}
/// Represents field attribute information
pub struct Field {
name: MultiName,
skip_serializing: bool,
skip_deserializing: bool,
skip_serializing_if: Option<syn::ExprPath>,