]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/deriving/decodable.rs
auto merge of #13143 : gentlefolk/rust/issue-9227, r=michaelwoerister
[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         attributes: Vec::new(),
32         path: Path::new_(vec!("serialize", "Decodable"), None,
33                          vec!(~Literal(Path::new_local("__D")),
34                               ~Literal(Path::new_local("__E"))), true),
35         additional_bounds: Vec::new(),
36         generics: LifetimeBounds {
37             lifetimes: Vec::new(),
38             bounds: vec!(("__D", vec!(Path::new_(
39                             vec!("serialize", "Decoder"), None,
40                             vec!(~Literal(Path::new_local("__E"))), true))),
41                          ("__E", vec!()))
42         },
43         methods: vec!(
44             MethodDef {
45                 name: "decode",
46                 generics: LifetimeBounds::empty(),
47                 explicit_self: None,
48                 args: vec!(Ptr(~Literal(Path::new_local("__D")),
49                             Borrowed(None, MutMutable))),
50                 ret_ty: Literal(Path::new_(vec!("std", "result", "Result"), None,
51                                           vec!(~Self, ~Literal(Path::new_local("__E"))), true)),
52                 inline: false,
53                 const_nonmatching: true,
54                 combine_substructure: decodable_substructure,
55             })
56     };
57
58     trait_def.expand(cx, mitem, item, push)
59 }
60
61 fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
62                           substr: &Substructure) -> @Expr {
63     let decoder = substr.nonself_args[0];
64     let recurse = vec!(cx.ident_of("serialize"),
65                     cx.ident_of("Decodable"),
66                     cx.ident_of("decode"));
67     // throw an underscore in front to suppress unused variable warnings
68     let blkarg = cx.ident_of("_d");
69     let blkdecoder = cx.expr_ident(trait_span, blkarg);
70     let calldecode = cx.expr_call_global(trait_span, recurse, vec!(blkdecoder));
71     let lambdadecode = cx.lambda_expr_1(trait_span, calldecode, blkarg);
72
73     return match *substr.fields {
74         StaticStruct(_, ref summary) => {
75             let nfields = match *summary {
76                 Unnamed(ref fields) => fields.len(),
77                 Named(ref fields) => fields.len()
78             };
79             let read_struct_field = cx.ident_of("read_struct_field");
80
81             let result = decode_static_fields(cx,
82                                               trait_span,
83                                               substr.type_ident,
84                                               summary,
85                                               |cx, span, name, field| {
86                 cx.expr_try(span,
87                     cx.expr_method_call(span, blkdecoder, read_struct_field,
88                                         vec!(cx.expr_str(span, name),
89                                           cx.expr_uint(span, field),
90                                           lambdadecode)))
91             });
92             let result = cx.expr_ok(trait_span, result);
93             cx.expr_method_call(trait_span,
94                                 decoder,
95                                 cx.ident_of("read_struct"),
96                                 vec!(
97                 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
98                 cx.expr_uint(trait_span, nfields),
99                 cx.lambda_expr_1(trait_span, result, blkarg)
100             ))
101         }
102         StaticEnum(_, ref fields) => {
103             let variant = cx.ident_of("i");
104
105             let mut arms = Vec::new();
106             let mut variants = Vec::new();
107             let rvariant_arg = cx.ident_of("read_enum_variant_arg");
108
109             for (i, &(name, v_span, ref parts)) in fields.iter().enumerate() {
110                 variants.push(cx.expr_str(v_span, token::get_ident(name)));
111
112                 let decoded = decode_static_fields(cx,
113                                                    v_span,
114                                                    name,
115                                                    parts,
116                                                    |cx, span, _, field| {
117                     let idx = cx.expr_uint(span, field);
118                     cx.expr_try(span,
119                         cx.expr_method_call(span, blkdecoder, rvariant_arg,
120                                             vec!(idx, lambdadecode)))
121                 });
122
123                 arms.push(cx.arm(v_span,
124                                  vec!(cx.pat_lit(v_span, cx.expr_uint(v_span, i))),
125                                  decoded));
126             }
127
128             arms.push(cx.arm_unreachable(trait_span));
129
130             let result = cx.expr_ok(trait_span,
131                                     cx.expr_match(trait_span,
132                                                   cx.expr_ident(trait_span, variant), arms));
133             let lambda = cx.lambda_expr(trait_span, vec!(blkarg, variant), result);
134             let variant_vec = cx.expr_vec(trait_span, variants);
135             let result = cx.expr_method_call(trait_span, blkdecoder,
136                                              cx.ident_of("read_enum_variant"),
137                                              vec!(variant_vec, lambda));
138             cx.expr_method_call(trait_span,
139                                 decoder,
140                                 cx.ident_of("read_enum"),
141                                 vec!(
142                 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
143                 cx.lambda_expr_1(trait_span, result, blkarg)
144             ))
145         }
146         _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Decodable)")
147     };
148 }
149
150 /// Create a decoder for a single enum variant/struct:
151 /// - `outer_pat_ident` is the name of this enum variant/struct
152 /// - `getarg` should retrieve the `uint`-th field with name `@str`.
153 fn decode_static_fields(cx: &mut ExtCtxt,
154                         trait_span: Span,
155                         outer_pat_ident: Ident,
156                         fields: &StaticFields,
157                         getarg: |&mut ExtCtxt, Span, InternedString, uint| -> @Expr)
158                         -> @Expr {
159     match *fields {
160         Unnamed(ref fields) => {
161             if fields.is_empty() {
162                 cx.expr_ident(trait_span, outer_pat_ident)
163             } else {
164                 let fields = fields.iter().enumerate().map(|(i, &span)| {
165                     getarg(cx, span,
166                            token::intern_and_get_ident(format!("_field{}",
167                                                                i)),
168                            i)
169                 }).collect();
170
171                 cx.expr_call_ident(trait_span, outer_pat_ident, fields)
172             }
173         }
174         Named(ref fields) => {
175             // use the field's span to get nicer error messages.
176             let fields = fields.iter().enumerate().map(|(i, &(name, span))| {
177                 let arg = getarg(cx, span, token::get_ident(name), i);
178                 cx.field_imm(span, name, arg)
179             }).collect();
180             cx.expr_struct_ident(trait_span, outer_pat_ident, fields)
181         }
182     }
183 }