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