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