]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/deriving/encodable.rs
concerning well-formed suggestions for unused shorthand field patterns
[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 `#[derive(Encodable)]`
12 //! (and `Decodable`, in decodable.rs) extension.  The idea here is that
13 //! type-defining items may be tagged with `#[derive(Encodable, Decodable)]`.
14 //!
15 //! For example, a type like:
16 //!
17 //! ```
18 //! #[derive(Encodable, Decodable)]
19 //! struct Node { id: usize }
20 //! ```
21 //!
22 //! would generate two implementations like:
23 //!
24 //! ```
25 //! # struct Node { id: usize }
26 //! impl<S: Encoder<E>, E> Encodable<S, E> for Node {
27 //!     fn encode(&self, s: &mut S) -> Result<(), E> {
28 //!         s.emit_struct("Node", 1, |this| {
29 //!             this.emit_struct_field("id", 0, |this| {
30 //!                 Encodable::encode(&self.id, this)
31 //!                 /* this.emit_usize(self.id) can also be used */
32 //!             })
33 //!         })
34 //!     }
35 //! }
36 //!
37 //! impl<D: Decoder<E>, E> Decodable<D, E> for Node {
38 //!     fn decode(d: &mut D) -> Result<Node, E> {
39 //!         d.read_struct("Node", 1, |this| {
40 //!             match this.read_struct_field("id", 0, |this| Decodable::decode(this)) {
41 //!                 Ok(id) => Ok(Node { id: id }),
42 //!                 Err(e) => Err(e),
43 //!             }
44 //!         })
45 //!     }
46 //! }
47 //! ```
48 //!
49 //! Other interesting scenarios are when the item has type parameters or
50 //! references other non-built-in types.  A type definition like:
51 //!
52 //! ```
53 //! # #[derive(Encodable, Decodable)] struct Span;
54 //! #[derive(Encodable, Decodable)]
55 //! struct Spanned<T> { node: T, span: Span }
56 //! ```
57 //!
58 //! would yield functions like:
59 //!
60 //! ```
61 //! # #[derive(Encodable, Decodable)] struct Span;
62 //! # struct Spanned<T> { node: T, span: Span }
63 //! impl<
64 //!     S: Encoder<E>,
65 //!     E,
66 //!     T: Encodable<S, E>
67 //! > Encodable<S, E> for Spanned<T> {
68 //!     fn encode(&self, s: &mut S) -> Result<(), E> {
69 //!         s.emit_struct("Spanned", 2, |this| {
70 //!             this.emit_struct_field("node", 0, |this| self.node.encode(this))
71 //!                 .unwrap();
72 //!             this.emit_struct_field("span", 1, |this| self.span.encode(this))
73 //!         })
74 //!     }
75 //! }
76 //!
77 //! impl<
78 //!     D: Decoder<E>,
79 //!     E,
80 //!     T: Decodable<D, E>
81 //! > Decodable<D, E> for Spanned<T> {
82 //!     fn decode(d: &mut D) -> Result<Spanned<T>, E> {
83 //!         d.read_struct("Spanned", 2, |this| {
84 //!             Ok(Spanned {
85 //!                 node: this.read_struct_field("node", 0, |this| Decodable::decode(this))
86 //!                     .unwrap(),
87 //!                 span: this.read_struct_field("span", 1, |this| Decodable::decode(this))
88 //!                     .unwrap(),
89 //!             })
90 //!         })
91 //!     }
92 //! }
93 //! ```
94
95 use deriving::{self, pathvec_std};
96 use deriving::generic::*;
97 use deriving::generic::ty::*;
98 use deriving::warn_if_deprecated;
99
100 use syntax::ast::{Expr, ExprKind, MetaItem, Mutability};
101 use syntax::ext::base::{Annotatable, ExtCtxt};
102 use syntax::ext::build::AstBuilder;
103 use syntax::ptr::P;
104 use syntax::symbol::Symbol;
105 use syntax_pos::Span;
106
107 pub fn expand_deriving_rustc_encodable(cx: &mut ExtCtxt,
108                                        span: Span,
109                                        mitem: &MetaItem,
110                                        item: &Annotatable,
111                                        push: &mut FnMut(Annotatable)) {
112     expand_deriving_encodable_imp(cx, span, mitem, item, push, "rustc_serialize")
113 }
114
115 pub fn expand_deriving_encodable(cx: &mut ExtCtxt,
116                                  span: Span,
117                                  mitem: &MetaItem,
118                                  item: &Annotatable,
119                                  push: &mut FnMut(Annotatable)) {
120     warn_if_deprecated(cx, span, "Encodable");
121     expand_deriving_encodable_imp(cx, span, mitem, item, push, "serialize")
122 }
123
124 fn expand_deriving_encodable_imp(cx: &mut ExtCtxt,
125                                  span: Span,
126                                  mitem: &MetaItem,
127                                  item: &Annotatable,
128                                  push: &mut FnMut(Annotatable),
129                                  krate: &'static str) {
130     let typaram = &*deriving::hygienic_type_parameter(item, "__S");
131
132     let trait_def = TraitDef {
133         span,
134         attributes: Vec::new(),
135         path: Path::new_(vec![krate, "Encodable"], None, vec![], PathKind::Global),
136         additional_bounds: Vec::new(),
137         generics: LifetimeBounds::empty(),
138         is_unsafe: false,
139         supports_unions: false,
140         methods: vec![
141             MethodDef {
142                 name: "encode",
143                 generics: LifetimeBounds {
144                     lifetimes: Vec::new(),
145                     bounds: vec![
146                         (typaram,
147                          vec![Path::new_(vec![krate, "Encoder"], None, vec![], PathKind::Global)])
148                     ],
149                 },
150                 explicit_self: borrowed_explicit_self(),
151                 args: vec![Ptr(Box::new(Literal(Path::new_local(typaram))),
152                            Borrowed(None, Mutability::Mutable))],
153                 ret_ty: Literal(Path::new_(
154                     pathvec_std!(cx, result::Result),
155                     None,
156                     vec![Box::new(Tuple(Vec::new())), Box::new(Literal(Path::new_(
157                         vec![typaram, "Error"], None, vec![], PathKind::Local
158                     )))],
159                     PathKind::Std
160                 )),
161                 attributes: Vec::new(),
162                 is_unsafe: false,
163                 unify_fieldless_variants: false,
164                 combine_substructure: combine_substructure(Box::new(|a, b, c| {
165                     encodable_substructure(a, b, c, krate)
166                 })),
167             }
168         ],
169         associated_types: Vec::new(),
170     };
171
172     trait_def.expand(cx, mitem, item, push)
173 }
174
175 fn encodable_substructure(cx: &mut ExtCtxt,
176                           trait_span: Span,
177                           substr: &Substructure,
178                           krate: &'static str)
179                           -> P<Expr> {
180     let encoder = substr.nonself_args[0].clone();
181     // throw an underscore in front to suppress unused variable warnings
182     let blkarg = cx.ident_of("_e");
183     let blkencoder = cx.expr_ident(trait_span, blkarg);
184     let fn_path = cx.expr_path(cx.path_global(trait_span,
185                                               vec![cx.ident_of(krate),
186                                                    cx.ident_of("Encodable"),
187                                                    cx.ident_of("encode")]));
188
189     return match *substr.fields {
190         Struct(_, ref fields) => {
191             let emit_struct_field = cx.ident_of("emit_struct_field");
192             let mut stmts = Vec::new();
193             for (i, &FieldInfo { name, ref self_, span, .. }) in fields.iter().enumerate() {
194                 let name = match name {
195                     Some(id) => id.name,
196                     None => Symbol::intern(&format!("_field{}", i)),
197                 };
198                 let self_ref = cx.expr_addr_of(span, self_.clone());
199                 let enc = cx.expr_call(span, fn_path.clone(), vec![self_ref, blkencoder.clone()]);
200                 let lambda = cx.lambda1(span, enc, blkarg);
201                 let call = cx.expr_method_call(span,
202                                                blkencoder.clone(),
203                                                emit_struct_field,
204                                                vec![cx.expr_str(span, name),
205                                                     cx.expr_usize(span, i),
206                                                     lambda]);
207
208                 // last call doesn't need a try!
209                 let last = fields.len() - 1;
210                 let call = if i != last {
211                     cx.expr_try(span, call)
212                 } else {
213                     cx.expr(span, ExprKind::Ret(Some(call)))
214                 };
215                 stmts.push(cx.stmt_expr(call));
216             }
217
218             // unit structs have no fields and need to return Ok()
219             if stmts.is_empty() {
220                 let ok = cx.expr_ok(trait_span, cx.expr_tuple(trait_span, vec![]));
221                 let ret_ok = cx.expr(trait_span, ExprKind::Ret(Some(ok)));
222                 stmts.push(cx.stmt_expr(ret_ok));
223             }
224
225             let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg);
226             cx.expr_method_call(trait_span,
227                                 encoder,
228                                 cx.ident_of("emit_struct"),
229                                 vec![cx.expr_str(trait_span, substr.type_ident.name),
230                                      cx.expr_usize(trait_span, fields.len()),
231                                      blk])
232         }
233
234         EnumMatching(idx, _, variant, ref fields) => {
235             // We're not generating an AST that the borrow checker is expecting,
236             // so we need to generate a unique local variable to take the
237             // mutable loan out on, otherwise we get conflicts which don't
238             // actually exist.
239             let me = cx.stmt_let(trait_span, false, blkarg, encoder);
240             let encoder = cx.expr_ident(trait_span, blkarg);
241             let emit_variant_arg = cx.ident_of("emit_enum_variant_arg");
242             let mut stmts = Vec::new();
243             if !fields.is_empty() {
244                 let last = fields.len() - 1;
245                 for (i, &FieldInfo { ref self_, span, .. }) in fields.iter().enumerate() {
246                     let self_ref = cx.expr_addr_of(span, self_.clone());
247                     let enc =
248                         cx.expr_call(span, fn_path.clone(), vec![self_ref, blkencoder.clone()]);
249                     let lambda = cx.lambda1(span, enc, blkarg);
250                     let call = cx.expr_method_call(span,
251                                                    blkencoder.clone(),
252                                                    emit_variant_arg,
253                                                    vec![cx.expr_usize(span, i), lambda]);
254                     let call = if i != last {
255                         cx.expr_try(span, call)
256                     } else {
257                         cx.expr(span, ExprKind::Ret(Some(call)))
258                     };
259                     stmts.push(cx.stmt_expr(call));
260                 }
261             } else {
262                 let ok = cx.expr_ok(trait_span, cx.expr_tuple(trait_span, vec![]));
263                 let ret_ok = cx.expr(trait_span, ExprKind::Ret(Some(ok)));
264                 stmts.push(cx.stmt_expr(ret_ok));
265             }
266
267             let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg);
268             let name = cx.expr_str(trait_span, variant.node.name.name);
269             let call = cx.expr_method_call(trait_span,
270                                            blkencoder,
271                                            cx.ident_of("emit_enum_variant"),
272                                            vec![name,
273                                                 cx.expr_usize(trait_span, idx),
274                                                 cx.expr_usize(trait_span, fields.len()),
275                                                 blk]);
276             let blk = cx.lambda1(trait_span, call, blkarg);
277             let ret = cx.expr_method_call(trait_span,
278                                           encoder,
279                                           cx.ident_of("emit_enum"),
280                                           vec![cx.expr_str(trait_span ,substr.type_ident.name),
281                                                blk]);
282             cx.expr_block(cx.block(trait_span, vec![me, cx.stmt_expr(ret)]))
283         }
284
285         _ => cx.bug("expected Struct or EnumMatching in derive(Encodable)"),
286     };
287 }