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