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