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