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