]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_builtin_macros/src/deriving/encodable.rs
New upstream version 1.48.0~beta.8+dfsg1
[rustc.git] / compiler / rustc_builtin_macros / src / 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::ptr::P;
93 use rustc_ast::{Expr, ExprKind, MetaItem, Mutability};
94 use rustc_expand::base::{Annotatable, ExtCtxt};
95 use rustc_span::symbol::{sym, Ident, 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 = sym::rustc_serialize;
106 let typaram = sym::__S;
107
108 let trait_def = TraitDef {
109 span,
110 attributes: Vec::new(),
111 path: Path::new_(vec![krate, sym::Encodable], None, vec![], PathKind::Global),
112 additional_bounds: Vec::new(),
113 generics: Bounds::empty(),
114 is_unsafe: false,
115 supports_unions: false,
116 methods: vec![MethodDef {
117 name: sym::encode,
118 generics: Bounds {
119 bounds: vec![(
120 typaram,
121 vec![Path::new_(vec![krate, sym::Encoder], None, vec![], PathKind::Global)],
122 )],
123 },
124 explicit_self: borrowed_explicit_self(),
125 args: vec![(
126 Ptr(Box::new(Literal(Path::new_local(typaram))), Borrowed(None, Mutability::Mut)),
127 // FIXME: we could use `sym::s` here, but making `s` a static
128 // symbol changes the symbol index ordering in a way that makes
129 // ui/lint/rfc-2457-non-ascii-idents/lint-confusable-idents.rs
130 // fail. The linting code should be fixed so that its output
131 // does not depend on the symbol index ordering.
132 Symbol::intern("s"),
133 )],
134 ret_ty: Literal(Path::new_(
135 pathvec_std!(result::Result),
136 None,
137 vec![
138 Box::new(Tuple(Vec::new())),
139 Box::new(Literal(Path::new_(
140 vec![typaram, sym::Error],
141 None,
142 vec![],
143 PathKind::Local,
144 ))),
145 ],
146 PathKind::Std,
147 )),
148 attributes: Vec::new(),
149 is_unsafe: false,
150 unify_fieldless_variants: false,
151 combine_substructure: combine_substructure(Box::new(|a, b, c| {
152 encodable_substructure(a, b, c, krate)
153 })),
154 }],
155 associated_types: Vec::new(),
156 };
157
158 trait_def.expand(cx, mitem, item, push)
159 }
160
161 fn encodable_substructure(
162 cx: &mut ExtCtxt<'_>,
163 trait_span: Span,
164 substr: &Substructure<'_>,
165 krate: Symbol,
166 ) -> P<Expr> {
167 let encoder = substr.nonself_args[0].clone();
168 // throw an underscore in front to suppress unused variable warnings
169 let blkarg = Ident::new(sym::_e, trait_span);
170 let blkencoder = cx.expr_ident(trait_span, blkarg);
171 let fn_path = cx.expr_path(cx.path_global(
172 trait_span,
173 vec![
174 Ident::new(krate, trait_span),
175 Ident::new(sym::Encodable, trait_span),
176 Ident::new(sym::encode, trait_span),
177 ],
178 ));
179
180 match *substr.fields {
181 Struct(_, ref fields) => {
182 let emit_struct_field = Ident::new(sym::emit_struct_field, trait_span);
183 let mut stmts = Vec::new();
184 for (i, &FieldInfo { name, ref self_, span, .. }) in fields.iter().enumerate() {
185 let name = match name {
186 Some(id) => id.name,
187 None => Symbol::intern(&format!("_field{}", i)),
188 };
189 let self_ref = cx.expr_addr_of(span, self_.clone());
190 let enc = cx.expr_call(span, fn_path.clone(), vec![self_ref, blkencoder.clone()]);
191 let lambda = cx.lambda1(span, enc, blkarg);
192 let call = cx.expr_method_call(
193 span,
194 blkencoder.clone(),
195 emit_struct_field,
196 vec![cx.expr_str(span, name), cx.expr_usize(span, i), lambda],
197 );
198
199 // last call doesn't need a try!
200 let last = fields.len() - 1;
201 let call = if i != last {
202 cx.expr_try(span, call)
203 } else {
204 cx.expr(span, ExprKind::Ret(Some(call)))
205 };
206
207 let stmt = cx.stmt_expr(call);
208 stmts.push(stmt);
209 }
210
211 // unit structs have no fields and need to return Ok()
212 let blk = if stmts.is_empty() {
213 let ok = cx.expr_ok(trait_span, cx.expr_tuple(trait_span, vec![]));
214 cx.lambda1(trait_span, ok, blkarg)
215 } else {
216 cx.lambda_stmts_1(trait_span, stmts, blkarg)
217 };
218
219 cx.expr_method_call(
220 trait_span,
221 encoder,
222 Ident::new(sym::emit_struct, trait_span),
223 vec![
224 cx.expr_str(trait_span, substr.type_ident.name),
225 cx.expr_usize(trait_span, fields.len()),
226 blk,
227 ],
228 )
229 }
230
231 EnumMatching(idx, _, variant, ref fields) => {
232 // We're not generating an AST that the borrow checker is expecting,
233 // so we need to generate a unique local variable to take the
234 // mutable loan out on, otherwise we get conflicts which don't
235 // actually exist.
236 let me = cx.stmt_let(trait_span, false, blkarg, encoder);
237 let encoder = cx.expr_ident(trait_span, blkarg);
238 let emit_variant_arg = Ident::new(sym::emit_enum_variant_arg, trait_span);
239 let mut stmts = Vec::new();
240 if !fields.is_empty() {
241 let last = fields.len() - 1;
242 for (i, &FieldInfo { ref self_, span, .. }) in fields.iter().enumerate() {
243 let self_ref = cx.expr_addr_of(span, self_.clone());
244 let enc =
245 cx.expr_call(span, fn_path.clone(), vec![self_ref, blkencoder.clone()]);
246 let lambda = cx.lambda1(span, enc, blkarg);
247 let call = cx.expr_method_call(
248 span,
249 blkencoder.clone(),
250 emit_variant_arg,
251 vec![cx.expr_usize(span, i), lambda],
252 );
253 let call = if i != last {
254 cx.expr_try(span, call)
255 } else {
256 cx.expr(span, ExprKind::Ret(Some(call)))
257 };
258 stmts.push(cx.stmt_expr(call));
259 }
260 } else {
261 let ok = cx.expr_ok(trait_span, cx.expr_tuple(trait_span, vec![]));
262 let ret_ok = cx.expr(trait_span, ExprKind::Ret(Some(ok)));
263 stmts.push(cx.stmt_expr(ret_ok));
264 }
265
266 let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg);
267 let name = cx.expr_str(trait_span, variant.ident.name);
268 let call = cx.expr_method_call(
269 trait_span,
270 blkencoder,
271 Ident::new(sym::emit_enum_variant, trait_span),
272 vec![
273 name,
274 cx.expr_usize(trait_span, idx),
275 cx.expr_usize(trait_span, fields.len()),
276 blk,
277 ],
278 );
279 let blk = cx.lambda1(trait_span, call, blkarg);
280 let ret = cx.expr_method_call(
281 trait_span,
282 encoder,
283 Ident::new(sym::emit_enum, trait_span),
284 vec![cx.expr_str(trait_span, substr.type_ident.name), blk],
285 );
286 cx.expr_block(cx.block(trait_span, vec![me, cx.stmt_expr(ret)]))
287 }
288
289 _ => cx.bug("expected Struct or EnumMatching in derive(Encodable)"),
290 }
291 }