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