]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/deriving/encodable.rs
auto merge of #13149 : brson/rust/rustdoclogo, r=alexcrichton
[rust.git] / src / libsyntax / ext / deriving / encodable.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
13 The compiler code necessary to implement the `#[deriving(Encodable)]`
14 (and `Decodable`, in decodable.rs) extension.  The idea here is that
15 type-defining items may be tagged with `#[deriving(Encodable, Decodable)]`.
16
17 For example, a type like:
18
19 ```ignore
20 #[deriving(Encodable, Decodable)]
21 struct Node { id: uint }
22 ```
23
24 would generate two implementations like:
25
26 ```ignore
27 impl<S:serialize::Encoder> Encodable<S> for Node {
28     fn encode(&self, s: &S) {
29         s.emit_struct("Node", 1, || {
30             s.emit_field("id", 0, || s.emit_uint(self.id))
31         })
32     }
33 }
34
35 impl<D:Decoder> Decodable for node_id {
36     fn decode(d: &D) -> Node {
37         d.read_struct("Node", 1, || {
38             Node {
39                 id: d.read_field(~"x", 0, || decode(d))
40             }
41         })
42     }
43 }
44 ```
45
46 Other interesting scenarios are whe the item has type parameters or
47 references other non-built-in types.  A type definition like:
48
49 ```ignore
50 #[deriving(Encodable, Decodable)]
51 struct spanned<T> { node: T, span: Span }
52 ```
53
54 would yield functions like:
55
56 ```ignore
57     impl<
58         S: Encoder,
59         T: Encodable<S>
60     > spanned<T>: Encodable<S> {
61         fn encode<S:Encoder>(s: &S) {
62             s.emit_rec(|| {
63                 s.emit_field("node", 0, || self.node.encode(s));
64                 s.emit_field("span", 1, || self.span.encode(s));
65             })
66         }
67     }
68
69     impl<
70         D: Decoder,
71         T: Decodable<D>
72     > spanned<T>: Decodable<D> {
73         fn decode(d: &D) -> spanned<T> {
74             d.read_rec(|| {
75                 {
76                     node: d.read_field(~"node", 0, || decode(d)),
77                     span: d.read_field(~"span", 1, || decode(d)),
78                 }
79             })
80         }
81     }
82 ```
83 */
84
85 use ast::{MetaItem, Item, Expr, ExprRet, MutMutable, LitNil};
86 use codemap::Span;
87 use ext::base::ExtCtxt;
88 use ext::build::AstBuilder;
89 use ext::deriving::generic::*;
90 use parse::token;
91
92 pub fn expand_deriving_encodable(cx: &mut ExtCtxt,
93                                  span: Span,
94                                  mitem: @MetaItem,
95                                  item: @Item,
96                                  push: |@Item|) {
97     let trait_def = TraitDef {
98         span: span,
99         attributes: Vec::new(),
100         path: Path::new_(vec!("serialize", "Encodable"), None,
101                          vec!(~Literal(Path::new_local("__S")),
102                               ~Literal(Path::new_local("__E"))), true),
103         additional_bounds: Vec::new(),
104         generics: LifetimeBounds {
105             lifetimes: Vec::new(),
106             bounds: vec!(("__S", vec!(Path::new_(
107                             vec!("serialize", "Encoder"), None,
108                             vec!(~Literal(Path::new_local("__E"))), true))),
109                          ("__E", vec!()))
110         },
111         methods: vec!(
112             MethodDef {
113                 name: "encode",
114                 generics: LifetimeBounds::empty(),
115                 explicit_self: borrowed_explicit_self(),
116                 args: vec!(Ptr(~Literal(Path::new_local("__S")),
117                             Borrowed(None, MutMutable))),
118                 ret_ty: Literal(Path::new_(vec!("std", "result", "Result"),
119                                            None,
120                                            vec!(~Tuple(Vec::new()),
121                                                 ~Literal(Path::new_local("__E"))),
122                                            true)),
123                 inline: false,
124                 const_nonmatching: true,
125                 combine_substructure: encodable_substructure,
126             })
127     };
128
129     trait_def.expand(cx, mitem, item, push)
130 }
131
132 fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
133                           substr: &Substructure) -> @Expr {
134     let encoder = substr.nonself_args[0];
135     // throw an underscore in front to suppress unused variable warnings
136     let blkarg = cx.ident_of("_e");
137     let blkencoder = cx.expr_ident(trait_span, blkarg);
138     let encode = cx.ident_of("encode");
139
140     return match *substr.fields {
141         Struct(ref fields) => {
142             let emit_struct_field = cx.ident_of("emit_struct_field");
143             let mut stmts = Vec::new();
144             let last = fields.len() - 1;
145             for (i, &FieldInfo {
146                     name,
147                     self_,
148                     span,
149                     ..
150                 }) in fields.iter().enumerate() {
151                 let name = match name {
152                     Some(id) => token::get_ident(id),
153                     None => {
154                         token::intern_and_get_ident(format!("_field{}", i))
155                     }
156                 };
157                 let enc = cx.expr_method_call(span, self_, encode, vec!(blkencoder));
158                 let lambda = cx.lambda_expr_1(span, enc, blkarg);
159                 let call = cx.expr_method_call(span, blkencoder,
160                                                emit_struct_field,
161                                                vec!(cx.expr_str(span, name),
162                                                  cx.expr_uint(span, i),
163                                                  lambda));
164
165                 // last call doesn't need a try!
166                 let call = if i != last {
167                     cx.expr_try(span, call)
168                 } else {
169                     cx.expr(span, ExprRet(Some(call)))
170                 };
171                 stmts.push(cx.stmt_expr(call));
172             }
173
174             let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg);
175             cx.expr_method_call(trait_span,
176                                 encoder,
177                                 cx.ident_of("emit_struct"),
178                                 vec!(
179                 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
180                 cx.expr_uint(trait_span, fields.len()),
181                 blk
182             ))
183         }
184
185         EnumMatching(idx, variant, ref fields) => {
186             // We're not generating an AST that the borrow checker is expecting,
187             // so we need to generate a unique local variable to take the
188             // mutable loan out on, otherwise we get conflicts which don't
189             // actually exist.
190             let me = cx.stmt_let(trait_span, false, blkarg, encoder);
191             let encoder = cx.expr_ident(trait_span, blkarg);
192             let emit_variant_arg = cx.ident_of("emit_enum_variant_arg");
193             let mut stmts = Vec::new();
194             let last = fields.len() - 1;
195             for (i, &FieldInfo { self_, span, .. }) in fields.iter().enumerate() {
196                 let enc = cx.expr_method_call(span, self_, encode, vec!(blkencoder));
197                 let lambda = cx.lambda_expr_1(span, enc, blkarg);
198                 let call = cx.expr_method_call(span, blkencoder,
199                                                emit_variant_arg,
200                                                vec!(cx.expr_uint(span, i),
201                                                  lambda));
202                 let call = if i != last {
203                     cx.expr_try(span, call)
204                 } else {
205                     cx.expr(span, ExprRet(Some(call)))
206                 };
207                 stmts.push(cx.stmt_expr(call));
208             }
209
210             // enums with no fields need to return Ok()
211             if stmts.len() == 0 {
212                 let ret_ok = cx.expr(trait_span,
213                                      ExprRet(Some(cx.expr_ok(trait_span,
214                                                              cx.expr_lit(trait_span, LitNil)))));
215                 stmts.push(cx.stmt_expr(ret_ok));
216             }
217
218             let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg);
219             let name = cx.expr_str(trait_span, token::get_ident(variant.node.name));
220             let call = cx.expr_method_call(trait_span, blkencoder,
221                                            cx.ident_of("emit_enum_variant"),
222                                            vec!(name,
223                                              cx.expr_uint(trait_span, idx),
224                                              cx.expr_uint(trait_span, fields.len()),
225                                              blk));
226             let blk = cx.lambda_expr_1(trait_span, call, blkarg);
227             let ret = cx.expr_method_call(trait_span,
228                                           encoder,
229                                           cx.ident_of("emit_enum"),
230                                           vec!(
231                 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
232                 blk
233             ));
234             cx.expr_block(cx.block(trait_span, vec!(me), Some(ret)))
235         }
236
237         _ => cx.bug("expected Struct or EnumMatching in deriving(Encodable)")
238     };
239 }