]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/deriving/encodable.rs
auto merge of #12062 : kballard/rust/from_utf8_lossy, r=huonw
[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: &ExtCtxt,
86                                  span: Span,
87                                  mitem: @MetaItem,
88                                  in_items: ~[@Item]) -> ~[@Item] {
89     let trait_def = TraitDef {
90         cx: cx, span: span,
91
92         path: Path::new_(~["serialize", "Encodable"], None,
93                          ~[~Literal(Path::new_local("__E"))], true),
94         additional_bounds: ~[],
95         generics: LifetimeBounds {
96             lifetimes: ~[],
97             bounds: ~[("__E", ~[Path::new(~["serialize", "Encoder"])])],
98         },
99         methods: ~[
100             MethodDef {
101                 name: "encode",
102                 generics: LifetimeBounds::empty(),
103                 explicit_self: borrowed_explicit_self(),
104                 args: ~[Ptr(~Literal(Path::new_local("__E")),
105                             Borrowed(None, MutMutable))],
106                 ret_ty: nil_ty(),
107                 inline: false,
108                 const_nonmatching: true,
109                 combine_substructure: encodable_substructure,
110             },
111         ]
112     };
113
114     trait_def.expand(mitem, in_items)
115 }
116
117 fn encodable_substructure(cx: &ExtCtxt, trait_span: Span,
118                           substr: &Substructure) -> @Expr {
119     let encoder = substr.nonself_args[0];
120     // throw an underscore in front to suppress unused variable warnings
121     let blkarg = cx.ident_of("_e");
122     let blkencoder = cx.expr_ident(trait_span, blkarg);
123     let encode = cx.ident_of("encode");
124
125     return match *substr.fields {
126         Struct(ref fields) => {
127             let emit_struct_field = cx.ident_of("emit_struct_field");
128             let mut stmts = ~[];
129             for (i, &FieldInfo {
130                     name,
131                     self_,
132                     span,
133                     ..
134                 }) in fields.iter().enumerate() {
135                 let name = match name {
136                     Some(id) => token::get_ident(id.name),
137                     None => {
138                         token::intern_and_get_ident(format!("_field{}", i))
139                     }
140                 };
141                 let enc = cx.expr_method_call(span, self_, encode, ~[blkencoder]);
142                 let lambda = cx.lambda_expr_1(span, enc, blkarg);
143                 let call = cx.expr_method_call(span, blkencoder,
144                                                emit_struct_field,
145                                                ~[cx.expr_str(span, name),
146                                                  cx.expr_uint(span, i),
147                                                  lambda]);
148                 stmts.push(cx.stmt_expr(call));
149             }
150
151             let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg);
152             cx.expr_method_call(trait_span,
153                                 encoder,
154                                 cx.ident_of("emit_struct"),
155                                 ~[
156                 cx.expr_str(trait_span,
157                             token::get_ident(substr.type_ident.name)),
158                 cx.expr_uint(trait_span, fields.len()),
159                 blk
160             ])
161         }
162
163         EnumMatching(idx, variant, ref fields) => {
164             // We're not generating an AST that the borrow checker is expecting,
165             // so we need to generate a unique local variable to take the
166             // mutable loan out on, otherwise we get conflicts which don't
167             // actually exist.
168             let me = cx.stmt_let(trait_span, false, blkarg, encoder);
169             let encoder = cx.expr_ident(trait_span, blkarg);
170             let emit_variant_arg = cx.ident_of("emit_enum_variant_arg");
171             let mut stmts = ~[];
172             for (i, &FieldInfo { self_, span, .. }) in fields.iter().enumerate() {
173                 let enc = cx.expr_method_call(span, self_, encode, ~[blkencoder]);
174                 let lambda = cx.lambda_expr_1(span, enc, blkarg);
175                 let call = cx.expr_method_call(span, blkencoder,
176                                                emit_variant_arg,
177                                                ~[cx.expr_uint(span, i),
178                                                  lambda]);
179                 stmts.push(cx.stmt_expr(call));
180             }
181
182             let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg);
183             let name = cx.expr_str(trait_span,
184                                    token::get_ident(variant.node.name.name));
185             let call = cx.expr_method_call(trait_span, blkencoder,
186                                            cx.ident_of("emit_enum_variant"),
187                                            ~[name,
188                                              cx.expr_uint(trait_span, idx),
189                                              cx.expr_uint(trait_span, fields.len()),
190                                              blk]);
191             let blk = cx.lambda_expr_1(trait_span, call, blkarg);
192             let ret = cx.expr_method_call(trait_span,
193                                           encoder,
194                                           cx.ident_of("emit_enum"),
195                                           ~[
196                 cx.expr_str(trait_span,
197                             token::get_ident(substr.type_ident.name)),
198                 blk
199             ]);
200             cx.expr_block(cx.block(trait_span, ~[me], Some(ret)))
201         }
202
203         _ => cx.bug("expected Struct or EnumMatching in deriving(Encodable)")
204     };
205 }