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