]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/deriving/decodable.rs
auto merge of #12161 : aepsil0n/rust/docs/for-loop, r=alexcrichton
[rust.git] / src / libsyntax / ext / deriving / decodable.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 /*!
12 The compiler code necessary for #[deriving(Decodable)]. See
13 encodable.rs for more.
14 */
15
16 use ast::{MetaItem, Item, Expr, MutMutable, Ident};
17 use codemap::Span;
18 use ext::base::ExtCtxt;
19 use ext::build::AstBuilder;
20 use ext::deriving::generic::*;
21 use parse::token::InternedString;
22 use parse::token;
23
24 pub fn expand_deriving_decodable(cx: &mut ExtCtxt,
25                                  span: Span,
26                                  mitem: @MetaItem,
27                                  item: @Item,
28                                  push: |@Item|) {
29     let trait_def = TraitDef {
30         span: span,
31         path: Path::new_(~["serialize", "Decodable"], None,
32                          ~[~Literal(Path::new_local("__D"))], true),
33         additional_bounds: ~[],
34         generics: LifetimeBounds {
35             lifetimes: ~[],
36             bounds: ~[("__D", ~[Path::new(~["serialize", "Decoder"])])],
37         },
38         methods: ~[
39             MethodDef {
40                 name: "decode",
41                 generics: LifetimeBounds::empty(),
42                 explicit_self: None,
43                 args: ~[Ptr(~Literal(Path::new_local("__D")),
44                             Borrowed(None, MutMutable))],
45                 ret_ty: Self,
46                 inline: false,
47                 const_nonmatching: true,
48                 combine_substructure: decodable_substructure,
49             },
50         ]
51     };
52
53     trait_def.expand(cx, mitem, item, push)
54 }
55
56 fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
57                           substr: &Substructure) -> @Expr {
58     let decoder = substr.nonself_args[0];
59     let recurse = ~[cx.ident_of("serialize"),
60                     cx.ident_of("Decodable"),
61                     cx.ident_of("decode")];
62     // throw an underscore in front to suppress unused variable warnings
63     let blkarg = cx.ident_of("_d");
64     let blkdecoder = cx.expr_ident(trait_span, blkarg);
65     let calldecode = cx.expr_call_global(trait_span, recurse, ~[blkdecoder]);
66     let lambdadecode = cx.lambda_expr_1(trait_span, calldecode, blkarg);
67
68     return match *substr.fields {
69         StaticStruct(_, ref summary) => {
70             let nfields = match *summary {
71                 Unnamed(ref fields) => fields.len(),
72                 Named(ref fields) => fields.len()
73             };
74             let read_struct_field = cx.ident_of("read_struct_field");
75
76             let result = decode_static_fields(cx,
77                                               trait_span,
78                                               substr.type_ident,
79                                               summary,
80                                               |cx, span, name, field| {
81                 cx.expr_method_call(span, blkdecoder, read_struct_field,
82                                     ~[cx.expr_str(span, name),
83                                       cx.expr_uint(span, field),
84                                       lambdadecode])
85             });
86             cx.expr_method_call(trait_span,
87                                 decoder,
88                                 cx.ident_of("read_struct"),
89                                 ~[
90                 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
91                 cx.expr_uint(trait_span, nfields),
92                 cx.lambda_expr_1(trait_span, result, blkarg)
93             ])
94         }
95         StaticEnum(_, ref fields) => {
96             let variant = cx.ident_of("i");
97
98             let mut arms = ~[];
99             let mut variants = ~[];
100             let rvariant_arg = cx.ident_of("read_enum_variant_arg");
101
102             for (i, &(name, v_span, ref parts)) in fields.iter().enumerate() {
103                 variants.push(cx.expr_str(v_span, token::get_ident(name)));
104
105                 let decoded = decode_static_fields(cx,
106                                                    v_span,
107                                                    name,
108                                                    parts,
109                                                    |cx, span, _, field| {
110                     let idx = cx.expr_uint(span, field);
111                     cx.expr_method_call(span, blkdecoder, rvariant_arg,
112                                         ~[idx, lambdadecode])
113                 });
114
115                 arms.push(cx.arm(v_span,
116                                  ~[cx.pat_lit(v_span, cx.expr_uint(v_span, i))],
117                                  decoded));
118             }
119
120             arms.push(cx.arm_unreachable(trait_span));
121
122             let result = cx.expr_match(trait_span, cx.expr_ident(trait_span, variant), arms);
123             let lambda = cx.lambda_expr(trait_span, ~[blkarg, variant], result);
124             let variant_vec = cx.expr_vec(trait_span, variants);
125             let result = cx.expr_method_call(trait_span, blkdecoder,
126                                              cx.ident_of("read_enum_variant"),
127                                              ~[variant_vec, lambda]);
128             cx.expr_method_call(trait_span,
129                                 decoder,
130                                 cx.ident_of("read_enum"),
131                                 ~[
132                 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
133                 cx.lambda_expr_1(trait_span, result, blkarg)
134             ])
135         }
136         _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Decodable)")
137     };
138 }
139
140 /// Create a decoder for a single enum variant/struct:
141 /// - `outer_pat_ident` is the name of this enum variant/struct
142 /// - `getarg` should retrieve the `uint`-th field with name `@str`.
143 fn decode_static_fields(cx: &mut ExtCtxt,
144                         trait_span: Span,
145                         outer_pat_ident: Ident,
146                         fields: &StaticFields,
147                         getarg: |&mut ExtCtxt, Span, InternedString, uint| -> @Expr)
148                         -> @Expr {
149     match *fields {
150         Unnamed(ref fields) => {
151             if fields.is_empty() {
152                 cx.expr_ident(trait_span, outer_pat_ident)
153             } else {
154                 let fields = fields.iter().enumerate().map(|(i, &span)| {
155                     getarg(cx, span,
156                            token::intern_and_get_ident(format!("_field{}",
157                                                                i)),
158                            i)
159                 }).collect();
160
161                 cx.expr_call_ident(trait_span, outer_pat_ident, fields)
162             }
163         }
164         Named(ref fields) => {
165             // use the field's span to get nicer error messages.
166             let fields = fields.iter().enumerate().map(|(i, &(name, span))| {
167                 let arg = getarg(cx, span, token::get_ident(name), i);
168                 cx.field_imm(span, name, arg)
169             }).collect();
170             cx.expr_struct_ident(trait_span, outer_pat_ident, fields)
171         }
172     }
173 }