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