]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/deriving/decodable.rs
Merge pull request #20510 from tshepang/patch-6
[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 //! The compiler code necessary for `#[derive(Decodable)]`. See encodable.rs for more.
12
13 use ast;
14 use ast::{MetaItem, Item, Expr, MutMutable};
15 use codemap::Span;
16 use ext::base::ExtCtxt;
17 use ext::build::AstBuilder;
18 use ext::deriving::generic::*;
19 use ext::deriving::generic::ty::*;
20 use parse::token::InternedString;
21 use parse::token;
22 use ptr::P;
23
24 pub fn expand_deriving_rustc_decodable<F>(cx: &mut ExtCtxt,
25                                           span: Span,
26                                           mitem: &MetaItem,
27                                           item: &Item,
28                                           push: F) where
29     F: FnOnce(P<Item>),
30 {
31     expand_deriving_decodable_imp(cx, span, mitem, item, push, "rustc_serialize")
32 }
33
34 pub fn expand_deriving_decodable<F>(cx: &mut ExtCtxt,
35                                     span: Span,
36                                     mitem: &MetaItem,
37                                     item: &Item,
38                                     push: F) where
39     F: FnOnce(P<Item>),
40 {
41     expand_deriving_decodable_imp(cx, span, mitem, item, push, "serialize")
42 }
43
44 fn expand_deriving_decodable_imp<F>(cx: &mut ExtCtxt,
45                                     span: Span,
46                                     mitem: &MetaItem,
47                                     item: &Item,
48                                     push: F,
49                                     krate: &'static str) where
50     F: FnOnce(P<Item>),
51 {
52     let trait_def = TraitDef {
53         span: span,
54         attributes: Vec::new(),
55         path: Path::new_(vec!(krate, "Decodable"), None,
56                          vec!(box Literal(Path::new_local("__D")),
57                               box Literal(Path::new_local("__E"))), true),
58         additional_bounds: Vec::new(),
59         generics: LifetimeBounds {
60             lifetimes: Vec::new(),
61             bounds: vec!(("__D", vec!(Path::new_(
62                             vec!(krate, "Decoder"), None,
63                             vec!(box Literal(Path::new_local("__E"))), true))),
64                          ("__E", vec!()))
65         },
66         methods: vec!(
67             MethodDef {
68                 name: "decode",
69                 generics: LifetimeBounds::empty(),
70                 explicit_self: None,
71                 args: vec!(Ptr(box Literal(Path::new_local("__D")),
72                             Borrowed(None, MutMutable))),
73                 ret_ty: Literal(Path::new_(vec!("std", "result", "Result"), None,
74                                           vec!(box Self,
75                                                box Literal(Path::new_local("__E"))), true)),
76                 attributes: Vec::new(),
77                 combine_substructure: combine_substructure(|a, b, c| {
78                     decodable_substructure(a, b, c, krate)
79                 }),
80             })
81     };
82
83     trait_def.expand(cx, mitem, item, push)
84 }
85
86 fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
87                           substr: &Substructure,
88                           krate: &str) -> P<Expr> {
89     let decoder = substr.nonself_args[0].clone();
90     let recurse = vec!(cx.ident_of(krate),
91                     cx.ident_of("Decodable"),
92                     cx.ident_of("decode"));
93     // throw an underscore in front to suppress unused variable warnings
94     let blkarg = cx.ident_of("_d");
95     let blkdecoder = cx.expr_ident(trait_span, blkarg);
96     let calldecode = cx.expr_call_global(trait_span, recurse, vec!(blkdecoder.clone()));
97     let lambdadecode = cx.lambda_expr_1(trait_span, calldecode, blkarg);
98
99     return match *substr.fields {
100         StaticStruct(_, ref summary) => {
101             let nfields = match *summary {
102                 Unnamed(ref fields) => fields.len(),
103                 Named(ref fields) => fields.len()
104             };
105             let read_struct_field = cx.ident_of("read_struct_field");
106
107             let path = cx.path_ident(trait_span, substr.type_ident);
108             let result = decode_static_fields(cx,
109                                               trait_span,
110                                               path,
111                                               summary,
112                                               |cx, span, name, field| {
113                 cx.expr_try(span,
114                     cx.expr_method_call(span, blkdecoder.clone(), read_struct_field,
115                                         vec!(cx.expr_str(span, name),
116                                           cx.expr_uint(span, field),
117                                           lambdadecode.clone())))
118             });
119             let result = cx.expr_ok(trait_span, result);
120             cx.expr_method_call(trait_span,
121                                 decoder,
122                                 cx.ident_of("read_struct"),
123                                 vec!(
124                 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
125                 cx.expr_uint(trait_span, nfields),
126                 cx.lambda_expr_1(trait_span, result, blkarg)
127             ))
128         }
129         StaticEnum(_, ref fields) => {
130             let variant = cx.ident_of("i");
131
132             let mut arms = Vec::new();
133             let mut variants = Vec::new();
134             let rvariant_arg = cx.ident_of("read_enum_variant_arg");
135
136             for (i, &(name, v_span, ref parts)) in fields.iter().enumerate() {
137                 variants.push(cx.expr_str(v_span, token::get_ident(name)));
138
139                 let path = cx.path(trait_span, vec![substr.type_ident, name]);
140                 let decoded = decode_static_fields(cx,
141                                                    v_span,
142                                                    path,
143                                                    parts,
144                                                    |cx, span, _, field| {
145                     let idx = cx.expr_uint(span, field);
146                     cx.expr_try(span,
147                         cx.expr_method_call(span, blkdecoder.clone(), rvariant_arg,
148                                             vec!(idx, lambdadecode.clone())))
149                 });
150
151                 arms.push(cx.arm(v_span,
152                                  vec!(cx.pat_lit(v_span, cx.expr_uint(v_span, i))),
153                                  decoded));
154             }
155
156             arms.push(cx.arm_unreachable(trait_span));
157
158             let result = cx.expr_ok(trait_span,
159                                     cx.expr_match(trait_span,
160                                                   cx.expr_ident(trait_span, variant), arms));
161             let lambda = cx.lambda_expr(trait_span, vec!(blkarg, variant), result);
162             let variant_vec = cx.expr_vec(trait_span, variants);
163             let variant_vec = cx.expr_addr_of(trait_span, variant_vec);
164             let result = cx.expr_method_call(trait_span, blkdecoder,
165                                              cx.ident_of("read_enum_variant"),
166                                              vec!(variant_vec, lambda));
167             cx.expr_method_call(trait_span,
168                                 decoder,
169                                 cx.ident_of("read_enum"),
170                                 vec!(
171                 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
172                 cx.lambda_expr_1(trait_span, result, blkarg)
173             ))
174         }
175         _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Decodable)")
176     };
177 }
178
179 /// Create a decoder for a single enum variant/struct:
180 /// - `outer_pat_path` is the path to this enum variant/struct
181 /// - `getarg` should retrieve the `uint`-th field with name `@str`.
182 fn decode_static_fields<F>(cx: &mut ExtCtxt,
183                            trait_span: Span,
184                            outer_pat_path: ast::Path,
185                            fields: &StaticFields,
186                            mut getarg: F)
187                            -> P<Expr> where
188     F: FnMut(&mut ExtCtxt, Span, InternedString, uint) -> P<Expr>,
189 {
190     match *fields {
191         Unnamed(ref fields) => {
192             let path_expr = cx.expr_path(outer_pat_path);
193             if fields.is_empty() {
194                 path_expr
195             } else {
196                 let fields = fields.iter().enumerate().map(|(i, &span)| {
197                     getarg(cx, span,
198                            token::intern_and_get_ident(format!("_field{}",
199                                                                i)[]),
200                            i)
201                 }).collect();
202
203                 cx.expr_call(trait_span, path_expr, fields)
204             }
205         }
206         Named(ref fields) => {
207             // use the field's span to get nicer error messages.
208             let fields = fields.iter().enumerate().map(|(i, &(name, span))| {
209                 let arg = getarg(cx, span, token::get_ident(name), i);
210                 cx.field_imm(span, name, arg)
211             }).collect();
212             cx.expr_struct(trait_span, outer_pat_path, fields)
213         }
214     }
215 }