serde_codegen 0.7.9

Macros to auto-generate implementations for the serde framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
use aster;

use syntax::ast::{
    self,
    EnumDef,
    Ident,
    Item,
    MetaItem,
};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::parse::token::InternedString;
use syntax::ptr::P;

use attr;
use bound;
use error::Error;

pub fn expand_derive_deserialize(
    cx: &mut ExtCtxt,
    span: Span,
    meta_item: &MetaItem,
    annotatable: &Annotatable,
    push: &mut FnMut(Annotatable)
) {
    let item = match *annotatable {
        Annotatable::Item(ref item) => item,
        _ => {
            cx.span_err(
                meta_item.span,
                "`#[derive(Deserialize)]` may only be applied to structs and enums");
            return;
        }
    };

    let builder = aster::AstBuilder::new().span(span);

    let impl_item = match deserialize_item(cx, &builder, &item) {
        Ok(item) => item,
        Err(Error) => {
            // An error occured, but it should have been reported already.
            return;
        }
    };

    push(Annotatable::Item(impl_item))
}

fn deserialize_item(
    cx: &ExtCtxt,
    builder: &aster::AstBuilder,
    item: &Item,
) -> Result<P<ast::Item>, Error> {
    let generics = match item.node {
        ast::ItemKind::Struct(_, ref generics) => generics,
        ast::ItemKind::Enum(_, ref generics) => generics,
        _ => {
            cx.span_err(
                item.span,
                "`#[derive(Deserialize)]` may only be applied to structs and enums");
            return Err(Error);
        }
    };

    let container_attrs = try!(attr::ContainerAttrs::from_item(cx, item));

    let impl_generics = try!(build_impl_generics(cx, &builder, item, generics, &container_attrs));

    let ty = builder.ty().path()
        .segment(item.ident).with_generics(impl_generics.clone()).build()
        .build();

    let body = try!(deserialize_body(cx,
                                     &builder,
                                     &item,
                                     &impl_generics,
                                     ty.clone(),
                                     &container_attrs));

    let where_clause = &impl_generics.where_clause;

    let dummy_const = builder.id(format!("_IMPL_DESERIALIZE_FOR_{}", item.ident));

    Ok(quote_item!(cx,
        #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
        const $dummy_const: () = {
            extern crate serde as _serde;
            #[automatically_derived]
            impl $impl_generics _serde::de::Deserialize for $ty $where_clause {
                fn deserialize<__D>(deserializer: &mut __D) -> ::std::result::Result<$ty, __D::Error>
                    where __D: _serde::de::Deserializer,
                {
                    $body
                }
            }
        };
    ).unwrap())
}

// All the generics in the input, plus a bound `T: Deserialize` for each generic
// field type that will be deserialized by us, plus a bound `T: Default` for
// each generic field type that will be set to a default value.
fn build_impl_generics(
    cx: &ExtCtxt,
    builder: &aster::AstBuilder,
    item: &Item,
    generics: &ast::Generics,
    container_attrs: &attr::ContainerAttrs,
) -> Result<ast::Generics, Error> {
    let generics = bound::without_defaults(generics);

    let generics = try!(bound::with_where_predicates_from_fields(
        cx, builder, item, &generics,
        |attrs| attrs.de_bound()));

    match container_attrs.de_bound() {
        Some(predicates) => {
            let generics = bound::with_where_predicates(builder, &generics, predicates);
            Ok(generics)
        }
        None => {
            let generics = try!(bound::with_bound(cx, builder, item, &generics,
                needs_deserialize_bound,
                &builder.path().ids(&["_serde", "de", "Deserialize"]).build()));
            let generics = try!(bound::with_bound(cx, builder, item, &generics,
                requires_default,
                &builder.path().global().ids(&["std", "default", "Default"]).build()));
            Ok(generics)
        }
    }
}

// Fields with a `skip_deserializing` or `deserialize_with` attribute are not
// deserialized by us so we do not generate a bound. Fields with a `bound`
// attribute specify their own bound so we do not generate one. All other fields
// may need a `T: Deserialize` bound where T is the type of the field.
fn needs_deserialize_bound(_: &ast::StructField, attrs: &attr::FieldAttrs) -> bool {
    !attrs.skip_deserializing_field()
        && attrs.deserialize_with().is_none()
        && attrs.de_bound().is_none()
}

// Fields with a `default` attribute (not `default=...`), and fields with a
// `skip_deserializing` attribute that do not also have `default=...`.
fn requires_default(field: &ast::StructField, attrs: &attr::FieldAttrs) -> bool {
    for meta_items in field.attrs.iter().filter_map(attr::get_serde_meta_items) {
        for meta_item in meta_items {
            match meta_item.node {
                ast::MetaItemKind::Word(ref name) if name == &"default" => {
                    return true
                }
                ast::MetaItemKind::NameValue(ref name, _) if name == &"default" => {
                    return false
                }
                _ => {}
            }
        }
    }
    attrs.skip_deserializing_field()
}

fn deserialize_body(
    cx: &ExtCtxt,
    builder: &aster::AstBuilder,
    item: &Item,
    impl_generics: &ast::Generics,
    ty: P<ast::Ty>,
    container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
    match item.node {
        ast::ItemKind::Struct(ref variant_data, _) => {
            deserialize_item_struct(
                cx,
                builder,
                item,
                impl_generics,
                ty,
                item.span,
                variant_data,
                container_attrs,
            )
        }
        ast::ItemKind::Enum(ref enum_def, _) => {
            deserialize_item_enum(
                cx,
                builder,
                item.ident,
                impl_generics,
                ty,
                enum_def,
                container_attrs,
            )
        }
        _ => {
            cx.span_bug(item.span,
                        "expected ItemStruct or ItemEnum in #[derive(Deserialize)]")
        }
    }
}

fn deserialize_item_struct(
    cx: &ExtCtxt,
    builder: &aster::AstBuilder,
    item: &Item,
    impl_generics: &ast::Generics,
    ty: P<ast::Ty>,
    span: Span,
    variant_data: &ast::VariantData,
    container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
    match *variant_data {
        ast::VariantData::Unit(_) => {
            deserialize_unit_struct(
                cx,
                item.ident,
                container_attrs,
            )
        }
        ast::VariantData::Tuple(ref fields, _) => {
            if fields.iter().any(|field| field.ident.is_some()) {
                cx.span_bug(span, "tuple struct has named fields")
            }

            deserialize_tuple(
                cx,
                &builder,
                item.ident,
                None,
                impl_generics,
                ty,
                fields,
                container_attrs,
            )
        }
        ast::VariantData::Struct(ref fields, _) => {
            if fields.iter().any(|field| field.ident.is_none()) {
                cx.span_bug(span, "struct has unnamed fields")
            }

            deserialize_struct(
                cx,
                &builder,
                item.ident,
                None,
                impl_generics,
                ty,
                fields,
                container_attrs,
            )
        }
    }
}


// Build `__Visitor<A, B, ...>(PhantomData<A>, PhantomData<B>, ...)`
fn deserialize_visitor(
    builder: &aster::AstBuilder,
    trait_generics: &ast::Generics,
    forward_ty_params: Vec<ast::TyParam>,
    forward_tys: Vec<P<ast::Ty>>
) -> Result<(P<ast::Item>, P<ast::Ty>, P<ast::Expr>, ast::Generics), Error> {
    if trait_generics.ty_params.is_empty() && forward_tys.is_empty() {
        Ok((
            builder.item().tuple_struct("__Visitor").build(),
            builder.ty().id("__Visitor"),
            builder.expr().id("__Visitor"),
            trait_generics.clone(),
        ))
    } else {
        let placeholders : Vec<_> = trait_generics.ty_params.iter()
            .map(|t| builder.ty().id(t.ident))
            .collect();
        let mut trait_generics = trait_generics.clone();
        let mut ty_params = forward_ty_params.clone();
        ty_params.extend(trait_generics.ty_params.into_vec());
        trait_generics.ty_params = P::from_vec(ty_params);

        Ok((
            builder.item().tuple_struct("__Visitor")
                .generics().with(trait_generics.clone()).build()
                .with_tys({
                    let lifetimes = trait_generics.lifetimes.iter()
                        .map(|lifetime_def| {
                            builder.ty()
                                .phantom_data()
                                .ref_().lifetime(lifetime_def.lifetime.name)
                                .ty()
                                .unit()
                        });

                    let ty_params = trait_generics.ty_params.iter()
                        .map(|ty_param| {
                            builder.ty()
                                .phantom_data()
                                .id(ty_param.ident)
                        });

                    lifetimes.chain(ty_params)
                })
                .build(),
            builder.ty().path()
                .segment("__Visitor").with_generics(trait_generics.clone()).build()
                .build(),
            builder.expr().call()
                .path().segment("__Visitor")
                .with_tys(forward_tys)
                .with_tys(placeholders)
                .build().build()
                .with_args({
                    let len = trait_generics.lifetimes.len() + trait_generics.ty_params.len();

                    (0 .. len).map(|_| builder.expr().phantom_data())
                })
                .build(),
            trait_generics,
        ))
    }
}

fn deserializer_ty_param(builder: &aster::AstBuilder) -> ast::TyParam {
    builder.ty_param("__D")
        .trait_bound(builder.path()
                     .segment("_serde").build()
                     .segment("de").build()
                     .id("Deserializer")
                     .build())
        .build()
        .build()
}

fn deserializer_ty_arg(builder: &aster::AstBuilder) -> P<ast::Ty>{
    builder.ty().id("__D")
}

fn deserialize_unit_struct(
    cx: &ExtCtxt,
    type_ident: Ident,
    container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
    let type_name = container_attrs.name().deserialize_name_expr();

    Ok(quote_expr!(cx, {
        struct __Visitor;

        impl _serde::de::Visitor for __Visitor {
            type Value = $type_ident;

            #[inline]
            fn visit_unit<__E>(&mut self) -> ::std::result::Result<$type_ident, __E>
                where __E: _serde::de::Error,
            {
                Ok($type_ident)
            }

            #[inline]
            fn visit_seq<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<$type_ident, __V::Error>
                where __V: _serde::de::SeqVisitor,
            {
                try!(visitor.end());
                self.visit_unit()
            }
        }

        deserializer.deserialize_unit_struct($type_name, __Visitor)
    }))
}

fn deserialize_tuple(
    cx: &ExtCtxt,
    builder: &aster::AstBuilder,
    type_ident: Ident,
    variant_ident: Option<Ident>,
    impl_generics: &ast::Generics,
    ty: P<ast::Ty>,
    fields: &[ast::StructField],
    container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
    let where_clause = &impl_generics.where_clause;

    let (visitor_item, visitor_ty, visitor_expr, visitor_generics) = try!(deserialize_visitor(
        builder,
        impl_generics,
        vec![deserializer_ty_param(builder)],
        vec![deserializer_ty_arg(builder)],
    ));

    let is_enum = variant_ident.is_some();
    let type_path = match variant_ident {
        Some(variant_ident) => builder.path().id(type_ident).id(variant_ident).build(),
        None => builder.path().id(type_ident).build(),
    };

    let nfields = fields.len();
    let fields_with_attrs = try!(attr::fields_with_attrs(cx, fields));

    let visit_newtype_struct = if !is_enum && nfields == 1 {
        Some(try!(deserialize_newtype_struct(
            cx,
            builder,
            type_ident,
            &type_path,
            impl_generics,
            &fields_with_attrs[0],
        )))
    } else {
        None
    };

    let visit_seq_expr = try!(deserialize_seq(
        cx,
        builder,
        type_ident,
        type_path,
        impl_generics,
        &fields_with_attrs,
        false,
    ));

    let dispatch = if is_enum {
        quote_expr!(cx,
            visitor.visit_tuple($nfields, $visitor_expr))
    } else if nfields == 1 {
        let type_name = container_attrs.name().deserialize_name_expr();
        quote_expr!(cx,
            deserializer.deserialize_newtype_struct($type_name, $visitor_expr))
    } else {
        let type_name = container_attrs.name().deserialize_name_expr();
        quote_expr!(cx,
            deserializer.deserialize_tuple_struct($type_name, $nfields, $visitor_expr))
    };

    Ok(quote_expr!(cx, {
        $visitor_item

        impl $visitor_generics _serde::de::Visitor for $visitor_ty $where_clause {
            type Value = $ty;

            $visit_newtype_struct

            #[inline]
            fn visit_seq<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<$ty, __V::Error>
                where __V: _serde::de::SeqVisitor,
            {
                $visit_seq_expr
            }
        }

        $dispatch
    }))
}

fn deserialize_seq(
    cx: &ExtCtxt,
    builder: &aster::AstBuilder,
    type_ident: Ident,
    type_path: ast::Path,
    impl_generics: &ast::Generics,
    fields: &[(ast::StructField, attr::FieldAttrs)],
    is_struct: bool,
) -> Result<P<ast::Expr>, Error> {
    let let_values: Vec<_> = fields.iter()
        .enumerate()
        .map(|(i, &(ref field, ref attrs))| {
            let name = builder.id(format!("__field{}", i));
            if attrs.skip_deserializing_field() {
                let default = expr_is_missing(cx, attrs);
                quote_stmt!(cx,
                    let $name = $default;
                ).unwrap()
            } else {
                let visit = match attrs.deserialize_with() {
                    None => {
                        let field_ty = &field.ty;
                        quote_expr!(cx, try!(visitor.visit::<$field_ty>()))
                    }
                    Some(path) => {
                        let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
                            cx, builder, type_ident, impl_generics, &field.ty, path);
                        quote_expr!(cx, {
                            $wrapper
                            $wrapper_impl
                            try!(visitor.visit::<$wrapper_ty>()).map(|wrap| wrap.value)
                        })
                    }
                };
                quote_stmt!(cx,
                    let $name = match $visit {
                        Some(value) => { value },
                        None => {
                            return Err(_serde::de::Error::end_of_stream());
                        }
                    };
                ).unwrap()
            }
        })
        .collect();

    let result = if is_struct {
        builder.expr().struct_path(type_path)
            .with_id_exprs(
                fields.iter()
                    .enumerate()
                    .map(|(i, &(ref field, _))| {
                        (
                            match field.ident {
                                Some(name) => name.clone(),
                                None => {
                                    cx.span_bug(field.span, "struct contains unnamed fields")
                                }
                            },
                            builder.expr().id(format!("__field{}", i)),
                        )
                    })
            )
            .build()
    } else {
        builder.expr().call()
            .build_path(type_path)
            .with_args((0..fields.len()).map(|i| builder.expr().id(format!("__field{}", i))))
            .build()
    };

    Ok(quote_expr!(cx, {
        $let_values

        try!(visitor.end());

        Ok($result)
    }))
}

fn deserialize_newtype_struct(
    cx: &ExtCtxt,
    builder: &aster::AstBuilder,
    type_ident: Ident,
    type_path: &ast::Path,
    impl_generics: &ast::Generics,
    field: &(ast::StructField, attr::FieldAttrs),
) -> Result<Vec<ast::TokenTree>, Error> {
    let &(ref field, ref attrs) = field;
    let value = match attrs.deserialize_with() {
        None => {
            let field_ty = &field.ty;
            quote_expr!(cx,
                try!(<$field_ty as _serde::Deserialize>::deserialize(__e)))
        }
        Some(path) => {
            let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
                cx, builder, type_ident, impl_generics, &field.ty, path);
            quote_expr!(cx, {
                $wrapper
                $wrapper_impl
                try!(<$wrapper_ty as _serde::Deserialize>::deserialize(__e)).value
            })
        }
    };
    Ok(quote_tokens!(cx,
        #[inline]
        fn visit_newtype_struct<__E>(&mut self, __e: &mut __E) -> ::std::result::Result<Self::Value, __E::Error>
            where __E: _serde::de::Deserializer,
        {
            Ok($type_path($value))
        }
    ))
}

fn deserialize_struct(
    cx: &ExtCtxt,
    builder: &aster::AstBuilder,
    type_ident: Ident,
    variant_ident: Option<Ident>,
    impl_generics: &ast::Generics,
    ty: P<ast::Ty>,
    fields: &[ast::StructField],
    container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
    let where_clause = &impl_generics.where_clause;

    let (visitor_item, visitor_ty, visitor_expr, visitor_generics) = try!(deserialize_visitor(
        builder,
        &impl_generics,
        vec![deserializer_ty_param(builder)],
        vec![deserializer_ty_arg(builder)],
    ));

    let type_path = match variant_ident {
        Some(variant_ident) => builder.path().id(type_ident).id(variant_ident).build(),
        None => builder.path().id(type_ident).build(),
    };

    let fields_with_attrs = try!(attr::fields_with_attrs(cx, fields));

    let visit_seq_expr = try!(deserialize_seq(
        cx,
        builder,
        type_ident,
        type_path.clone(),
        impl_generics,
        &fields_with_attrs,
        true,
    ));

    let (field_visitor, fields_stmt, visit_map_expr) = try!(deserialize_struct_visitor(
        cx,
        builder,
        type_ident,
        type_path.clone(),
        impl_generics,
        &fields_with_attrs,
        container_attrs,
    ));

    let is_enum = variant_ident.is_some();
    let dispatch = if is_enum {
        quote_expr!(cx,
            visitor.visit_struct(FIELDS, $visitor_expr))
    } else {
        let type_name = container_attrs.name().deserialize_name_expr();
        quote_expr!(cx,
            deserializer.deserialize_struct($type_name, FIELDS, $visitor_expr))
    };

    Ok(quote_expr!(cx, {
        $field_visitor

        $visitor_item

        impl $visitor_generics _serde::de::Visitor for $visitor_ty $where_clause {
            type Value = $ty;

            #[inline]
            fn visit_seq<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<$ty, __V::Error>
                where __V: _serde::de::SeqVisitor,
            {
                $visit_seq_expr
            }

            #[inline]
            fn visit_map<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<$ty, __V::Error>
                where __V: _serde::de::MapVisitor,
            {
                $visit_map_expr
            }
        }

        $fields_stmt

        $dispatch
    }))
}

fn deserialize_item_enum(
    cx: &ExtCtxt,
    builder: &aster::AstBuilder,
    type_ident: Ident,
    impl_generics: &ast::Generics,
    ty: P<ast::Ty>,
    enum_def: &EnumDef,
    container_attrs: &attr::ContainerAttrs
) -> Result<P<ast::Expr>, Error> {
    let where_clause = &impl_generics.where_clause;

    let type_name = container_attrs.name().deserialize_name_expr();

    let variant_visitor = deserialize_field_visitor(
        cx,
        builder,
        try!(
            enum_def.variants.iter()
                .map(|variant| {
                    let attrs = try!(attr::VariantAttrs::from_variant(cx, variant));
                    Ok(attrs.name().deserialize_name())
                })
                .collect()
        ),
        container_attrs,
        true,
    );

    let variants_expr = builder.expr().ref_().slice()
        .with_exprs(
            enum_def.variants.iter()
                .map(|variant| {
                    builder.expr().str(variant.node.name)
                })
        )
        .build();

    let variants_stmt = quote_stmt!(cx,
        const VARIANTS: &'static [&'static str] = $variants_expr;
    ).unwrap();

    let ignored_arm = if container_attrs.deny_unknown_fields() {
        None
    } else {
        Some(quote_arm!(cx, __Field::__ignore => { Err(_serde::de::Error::end_of_stream()) }))
    };

    // Match arms to extract a variant from a string
    let mut variant_arms = vec![];
    for (i, variant) in enum_def.variants.iter().enumerate() {
        let variant_name = builder.pat().path()
            .id("__Field").id(format!("__field{}", i))
            .build();

        let expr = try!(deserialize_variant(
            cx,
            builder,
            type_ident,
            impl_generics,
            ty.clone(),
            variant,
            container_attrs,
        ));

        let arm = quote_arm!(cx, $variant_name => { $expr });
        variant_arms.push(arm);
    }
    variant_arms.extend(ignored_arm.into_iter());

    let (visitor_item, visitor_ty, visitor_expr, visitor_generics) = try!(deserialize_visitor(
        builder,
        impl_generics,
        vec![deserializer_ty_param(builder)],
        vec![deserializer_ty_arg(builder)],
    ));

    Ok(quote_expr!(cx, {
        $variant_visitor

        $visitor_item

        impl $visitor_generics _serde::de::EnumVisitor for $visitor_ty $where_clause {
            type Value = $ty;

            fn visit<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<$ty, __V::Error>
                where __V: _serde::de::VariantVisitor,
            {
                match try!(visitor.visit_variant()) {
                    $variant_arms
                }
            }
        }

        $variants_stmt

        deserializer.deserialize_enum($type_name, VARIANTS, $visitor_expr)
    }))
}

fn deserialize_variant(
    cx: &ExtCtxt,
    builder: &aster::AstBuilder,
    type_ident: Ident,
    generics: &ast::Generics,
    ty: P<ast::Ty>,
    variant: &ast::Variant,
    container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
    let variant_ident = variant.node.name;

    match variant.node.data {
        ast::VariantData::Unit(_) => {
            Ok(quote_expr!(cx, {
                try!(visitor.visit_unit());
                Ok($type_ident::$variant_ident)
            }))
        }
        ast::VariantData::Tuple(ref fields, _) if fields.len() == 1 => {
            deserialize_newtype_variant(
                cx,
                builder,
                type_ident,
                variant_ident,
                generics,
                &fields[0],
            )
        }
        ast::VariantData::Tuple(ref fields, _) => {
            deserialize_tuple(
                cx,
                builder,
                type_ident,
                Some(variant_ident),
                generics,
                ty,
                fields,
                container_attrs,
            )
        }
        ast::VariantData::Struct(ref fields, _) => {
            deserialize_struct(
                cx,
                builder,
                type_ident,
                Some(variant_ident),
                generics,
                ty,
                fields,
                container_attrs,
            )
        }
    }
}

fn deserialize_newtype_variant(
    cx: &ExtCtxt,
    builder: &aster::AstBuilder,
    type_ident: Ident,
    variant_ident: Ident,
    impl_generics: &ast::Generics,
    field: &ast::StructField,
) -> Result<P<ast::Expr>, Error> {
    let attrs = try!(attr::FieldAttrs::from_field(cx, 0, field));
    let visit = match attrs.deserialize_with() {
        None => {
            let field_ty = &field.ty;
            quote_expr!(cx, try!(visitor.visit_newtype::<$field_ty>()))
        }
        Some(path) => {
            let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
                cx, builder, type_ident, impl_generics, &field.ty, path);
            quote_expr!(cx, {
                $wrapper
                $wrapper_impl
                try!(visitor.visit_newtype::<$wrapper_ty>()).value
            })
        }
    };
    Ok(quote_expr!(cx, Ok($type_ident::$variant_ident($visit))))
}

fn deserialize_field_visitor(
    cx: &ExtCtxt,
    builder: &aster::AstBuilder,
    field_names: Vec<InternedString>,
    container_attrs: &attr::ContainerAttrs,
    is_variant: bool,
) -> Vec<P<ast::Item>> {
    // Create the field names for the fields.
    let field_idents: Vec<_> = (0 .. field_names.len())
        .map(|i| builder.id(format!("__field{}", i)))
        .collect();

    let ignore_variant = if container_attrs.deny_unknown_fields() {
        None
    } else {
        let skip_ident = builder.id("__ignore");
        Some(builder.variant(skip_ident).unit())
    };

    let field_enum = builder.item()
        .attr().allow(&["non_camel_case_types"])
        .enum_("__Field")
        .with_variants(
            field_idents.iter().map(|field_ident| {
                builder.variant(field_ident).unit()
            })
        )
        .with_variants(ignore_variant.into_iter())
        .build();

    let index_field_arms: Vec<_> = field_idents.iter()
        .enumerate()
        .map(|(field_index, field_ident)| {
            quote_arm!(cx, $field_index => { Ok(__Field::$field_ident) })
        })
        .collect();

    let (index_error_msg, unknown_ident) = if is_variant {
        (builder.expr().str("expected a variant"), builder.id("unknown_variant"))
    } else {
        (builder.expr().str("expected a field"), builder.id("unknown_field"))
    };

    let fallthrough_index_arm_expr = if !is_variant && !container_attrs.deny_unknown_fields() {
        quote_expr!(cx, Ok(__Field::__ignore))
    } else {
        quote_expr!(cx, {
            Err(_serde::de::Error::invalid_value($index_error_msg))
        })
    };

    let index_body = quote_expr!(cx,
        match value {
            $index_field_arms
            _ => $fallthrough_index_arm_expr
        }
    );

    // Convert the field names into byte strings.
    let str_field_names: Vec<_> = field_names.iter()
        .map(|name| builder.expr().lit().str(&name))
        .collect();

    // Match arms to extract a field from a string
    let str_field_arms: Vec<_> = field_idents.iter().zip(str_field_names.iter())
        .map(|(field_ident, field_name)| {
            quote_arm!(cx, $field_name => { Ok(__Field::$field_ident) })
        })
        .collect();

    let fallthrough_str_arm_expr = if !is_variant && !container_attrs.deny_unknown_fields() {
        quote_expr!(cx, Ok(__Field::__ignore))
    } else {
        quote_expr!(cx, Err(_serde::de::Error::$unknown_ident(value)))
    };

    let str_body = quote_expr!(cx,
        match value {
            $str_field_arms
            _ => $fallthrough_str_arm_expr
        }
    );

    // Convert the field names into byte strings.
    let bytes_field_names: Vec<_> = field_names.iter()
        .map(|name| {
            let name: &str = name;
            builder.expr().lit().byte_str(name)
        })
        .collect();

    // Match arms to extract a field from a string
    let bytes_field_arms: Vec<_> = field_idents.iter().zip(bytes_field_names.iter())
        .map(|(field_ident, field_name)| {
            quote_arm!(cx, $field_name => { Ok(__Field::$field_ident) })
        })
        .collect();

    let fallthrough_bytes_arm_expr = if !is_variant && !container_attrs.deny_unknown_fields() {
        quote_expr!(cx, Ok(__Field::__ignore))
    } else {
        quote_expr!(cx, {
            let value = ::std::string::String::from_utf8_lossy(value);
            Err(_serde::de::Error::$unknown_ident(&value))
        })
    };

    let bytes_body = quote_expr!(cx,
        match value {
            $bytes_field_arms
            _ => $fallthrough_bytes_arm_expr
        }
    );

    let impl_item = quote_item!(cx,
        impl _serde::de::Deserialize for __Field {
            #[inline]
            fn deserialize<__D>(deserializer: &mut __D) -> ::std::result::Result<__Field, __D::Error>
                where __D: _serde::de::Deserializer,
            {
                struct __FieldVisitor<__D> {
                    phantom: ::std::marker::PhantomData<__D>
                }

                impl<__D> _serde::de::Visitor for __FieldVisitor<__D>
                    where __D: _serde::de::Deserializer
                {
                    type Value = __Field;

                    fn visit_usize<__E>(&mut self, value: usize) -> ::std::result::Result<__Field, __E>
                        where __E: _serde::de::Error,
                    {
                        $index_body
                    }

                    fn visit_str<__E>(&mut self, value: &str) -> ::std::result::Result<__Field, __E>
                        where __E: _serde::de::Error,
                    {
                        $str_body
                    }

                    fn visit_bytes<__E>(&mut self, value: &[u8]) -> ::std::result::Result<__Field, __E>
                        where __E: _serde::de::Error,
                    {
                        $bytes_body
                    }
                }

                deserializer.deserialize_struct_field(
                    __FieldVisitor::<__D>{
                        phantom: ::std::marker::PhantomData
                    }
                )
            }
        }
    ).unwrap();

    vec![field_enum, impl_item]
}

fn deserialize_struct_visitor(
    cx: &ExtCtxt,
    builder: &aster::AstBuilder,
    type_ident: Ident,
    struct_path: ast::Path,
    impl_generics: &ast::Generics,
    fields: &[(ast::StructField, attr::FieldAttrs)],
    container_attrs: &attr::ContainerAttrs,
) -> Result<(Vec<P<ast::Item>>, ast::Stmt, P<ast::Expr>), Error> {
    let field_exprs = fields.iter()
        .map(|&(_, ref attrs)| attrs.name().deserialize_name())
        .collect();

    let field_visitor = deserialize_field_visitor(
        cx,
        builder,
        field_exprs,
        container_attrs,
        false,
    );

    let visit_map_expr = try!(deserialize_map(
        cx,
        builder,
        type_ident,
        struct_path,
        impl_generics,
        fields,
        container_attrs,
    ));

    let fields_expr = builder.expr().ref_().slice()
        .with_exprs(
            fields.iter()
                .map(|&(ref field, _)| {
                    match field.ident {
                        Some(name) => builder.expr().str(name),
                        None => {
                            cx.span_bug(field.span, "struct contains unnamed fields")
                        }
                    }
                })
        )
        .build();

    let fields_stmt = quote_stmt!(cx,
        const FIELDS: &'static [&'static str] = $fields_expr;
    ).unwrap();

    Ok((field_visitor, fields_stmt, visit_map_expr))
}

fn deserialize_map(
    cx: &ExtCtxt,
    builder: &aster::AstBuilder,
    type_ident: Ident,
    struct_path: ast::Path,
    impl_generics: &ast::Generics,
    fields: &[(ast::StructField, attr::FieldAttrs)],
    container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
    // Create the field names for the fields.
    let fields_attrs_names = fields.iter()
        .enumerate()
        .map(|(i, &(ref field, ref attrs))|
             (field, attrs, builder.id(format!("__field{}", i))))
        .collect::<Vec<_>>();

    // Declare each field that will be deserialized.
    let let_values: Vec<ast::Stmt> = fields_attrs_names.iter()
        .filter(|&&(_, ref attrs, _)| !attrs.skip_deserializing_field())
        .map(|&(field, _, name)| {
            let field_ty = &field.ty;
            quote_stmt!(cx, let mut $name: Option<$field_ty> = None;).unwrap()
        })
        .collect();

    // Match arms to extract a value for a field.
    let value_arms = fields_attrs_names.iter()
        .filter(|&&(_, ref attrs, _)| !attrs.skip_deserializing_field())
        .map(|&(ref field, ref attrs, name)| {
            let deser_name = attrs.name().deserialize_name();
            let name_str = builder.expr().lit().str(deser_name);

            let visit = match attrs.deserialize_with() {
                None => {
                    let field_ty = &field.ty;
                    quote_expr!(cx, try!(visitor.visit_value::<$field_ty>()))
                }
                Some(path) => {
                    let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
                        cx, builder, type_ident, impl_generics, &field.ty, path);
                    quote_expr!(cx, ({
                        $wrapper
                        $wrapper_impl
                        try!(visitor.visit_value::<$wrapper_ty>()).value
                    }))
                }
            };
            quote_arm!(cx,
                __Field::$name => {
                    if $name.is_some() {
                        return Err(<__V::Error as _serde::de::Error>::duplicate_field($name_str));
                    }
                    $name = Some($visit);
                }
            )
        })
        .collect::<Vec<_>>();

    // Match arms to ignore value for fields that have `skip_deserializing`.
    // Ignored even if `deny_unknown_fields` is set.
    let skipped_arms = fields_attrs_names.iter()
        .filter(|&&(_, ref attrs, _)| attrs.skip_deserializing_field())
        .map(|&(_, _, name)| {
            quote_arm!(cx,
                __Field::$name => {
                    try!(visitor.visit_value::<_serde::de::impls::IgnoredAny>());
                }
            )
        })
        .collect::<Vec<_>>();

    // Visit ignored values to consume them
    let ignored_arm = if container_attrs.deny_unknown_fields() {
        None
    } else {
        Some(quote_arm!(cx,
            _ => { try!(visitor.visit_value::<_serde::de::impls::IgnoredAny>()); }
        ))
    };

    let extract_values = fields_attrs_names.iter()
        .filter(|&&(_, ref attrs, _)| !attrs.skip_deserializing_field())
        .map(|&(_, ref attrs, name)| {
            let missing_expr = expr_is_missing(cx, attrs);

            Ok(quote_stmt!(cx,
                let $name = match $name {
                    Some($name) => $name,
                    None => $missing_expr
                };
            ).unwrap())
        })
        .collect::<Result<Vec<_>, _>>();

    let extract_values = try!(extract_values);

    let result = builder.expr().struct_path(struct_path)
        .with_id_exprs(
            fields_attrs_names.iter()
                .map(|&(field, attrs, name)| {
                    (
                        match field.ident {
                            Some(name) => name.clone(),
                            None => {
                                cx.span_bug(field.span, "struct contains unnamed fields")
                            }
                        },
                        if attrs.skip_deserializing_field() {
                            expr_is_missing(cx, attrs)
                        } else {
                            builder.expr().id(name)
                        }
                    )
                })
        )
        .build();

    Ok(quote_expr!(cx, {
        $let_values

        while let Some(key) = try!(visitor.visit_key::<__Field>()) {
            match key {
                $value_arms
                $skipped_arms
                $ignored_arm
            }
        }

        $extract_values

        try!(visitor.end());

        Ok($result)
    }))
}

/// This function wraps the expression in `#[serde(deserialize_with="...")]` in
/// a trait to prevent it from accessing the internal `Deserialize` state.
fn wrap_deserialize_with(
    cx: &ExtCtxt,
    builder: &aster::AstBuilder,
    type_ident: Ident,
    impl_generics: &ast::Generics,
    field_ty: &P<ast::Ty>,
    deserialize_with: &ast::Path,
) -> (ast::Stmt, ast::Stmt, ast::Path) {
    // Quasi-quoting doesn't do a great job of expanding generics into paths,
    // so manually build it.
    let wrapper_ty = builder.path()
        .segment("__SerdeDeserializeWithStruct")
            .with_generics(impl_generics.clone())
            .build()
        .build();

    let where_clause = &impl_generics.where_clause;

    let phantom_ty = builder.path()
        .segment(type_ident)
            .with_generics(builder.from_generics(impl_generics.clone())
                .strip_ty_params()
                .build())
            .build()
        .build();

    (
        quote_stmt!(cx,
            struct __SerdeDeserializeWithStruct $impl_generics $where_clause {
                value: $field_ty,
                phantom: ::std::marker::PhantomData<$phantom_ty>,
            }
        ).unwrap(),
        quote_stmt!(cx,
            impl $impl_generics _serde::de::Deserialize for $wrapper_ty $where_clause {
                fn deserialize<__D>(__d: &mut __D) -> ::std::result::Result<Self, __D::Error>
                    where __D: _serde::de::Deserializer
                {
                    let value = try!($deserialize_with(__d));
                    Ok(__SerdeDeserializeWithStruct {
                        value: value,
                        phantom: ::std::marker::PhantomData,
                    })
                }
            }
        ).unwrap(),
        wrapper_ty,
    )
}

fn expr_is_missing(
    cx: &ExtCtxt,
    attrs: &attr::FieldAttrs,
) -> P<ast::Expr> {
    if let Some(expr) = attrs.default_expr_if_missing() {
        return expr.clone();
    }
    let name = attrs.name().deserialize_name_expr();
    match attrs.deserialize_with() {
        None => {
            quote_expr!(cx, try!(visitor.missing_field($name)))
        }
        Some(_) => {
            quote_expr!(cx, return Err(
                <__V::Error as _serde::de::Error>::missing_field($name)))
        }
    }
}