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