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)]`.
6 //! For example, a type like:
9 //! #[derive(RustcEncodable, RustcDecodable)]
10 //! struct Node { id: usize }
13 //! would generate two implementations like:
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 */
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 }),
40 //! Other interesting scenarios are when the item has type parameters or
41 //! references other non-built-in types. A type definition like:
44 //! # #[derive(RustcEncodable, RustcDecodable)]
46 //! #[derive(RustcEncodable, RustcDecodable)]
47 //! struct Spanned<T> { node: T, span: Span }
50 //! would yield functions like:
53 //! # #[derive(RustcEncodable, RustcDecodable)]
55 //! # struct Spanned<T> { node: T, span: Span }
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))
65 //! this.emit_struct_field("span", 1, |this| self.span.encode(this))
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| {
78 //! node: this.read_struct_field("node", 0, |this| Decodable::decode(this))
80 //! span: this.read_struct_field("span", 1, |this| Decodable::decode(this))
88 use crate::deriving
::generic
::ty
::*;
89 use crate::deriving
::generic
::*;
90 use crate::deriving
::pathvec_std
;
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
;
98 pub fn expand_deriving_rustc_encodable(
103 push
: &mut dyn FnMut(Annotatable
),
105 let krate
= "rustc_serialize";
108 let trait_def
= TraitDef
{
110 attributes
: Vec
::new(),
111 path
: Path
::new_(vec
![krate
, "Encodable"], None
, vec
![], PathKind
::Global
),
112 additional_bounds
: Vec
::new(),
113 generics
: LifetimeBounds
::empty(),
115 supports_unions
: false,
116 methods
: vec
![MethodDef
{
118 generics
: LifetimeBounds
{
119 lifetimes
: Vec
::new(),
122 vec
![Path
::new_(vec
![krate
, "Encoder"], None
, vec
![], PathKind
::Global
)],
125 explicit_self
: borrowed_explicit_self(),
127 Ptr(Box
::new(Literal(Path
::new_local(typaram
))), Borrowed(None
, Mutability
::Mut
)),
130 ret_ty
: Literal(Path
::new_(
131 pathvec_std
!(cx
, result
::Result
),
134 Box
::new(Tuple(Vec
::new())),
135 Box
::new(Literal(Path
::new_(
136 vec
![typaram
, "Error"],
144 attributes
: Vec
::new(),
146 unify_fieldless_variants
: false,
147 combine_substructure
: combine_substructure(Box
::new(|a
, b
, c
| {
148 encodable_substructure(a
, b
, c
, krate
)
151 associated_types
: Vec
::new(),
154 trait_def
.expand(cx
, mitem
, item
, push
)
157 fn encodable_substructure(
158 cx
: &mut ExtCtxt
<'_
>,
160 substr
: &Substructure
<'_
>,
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(
170 cx
.ident_of(krate
, trait_span
),
171 cx
.ident_of("Encodable", trait_span
),
172 cx
.ident_of("encode", trait_span
),
176 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
{
183 None
=> Symbol
::intern(&format
!("_field{}", i
)),
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(
192 vec
![cx
.expr_str(span
, name
), cx
.expr_usize(span
, i
), lambda
],
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
)
200 cx
.expr(span
, ExprKind
::Ret(Some(call
)))
203 let stmt
= cx
.stmt_expr(call
);
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
)
212 cx
.lambda_stmts_1(trait_span
, stmts
, blkarg
)
218 cx
.ident_of("emit_struct", trait_span
),
220 cx
.expr_str(trait_span
, substr
.type_ident
.name
),
221 cx
.expr_usize(trait_span
, fields
.len()),
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
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());
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(
247 vec
![cx
.expr_usize(span
, i
), lambda
],
249 let call
= if i
!= last
{
250 cx
.expr_try(span
, call
)
252 cx
.expr(span
, ExprKind
::Ret(Some(call
)))
254 stmts
.push(cx
.stmt_expr(call
));
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
));
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(
267 cx
.ident_of("emit_enum_variant", trait_span
),
270 cx
.expr_usize(trait_span
, idx
),
271 cx
.expr_usize(trait_span
, fields
.len()),
275 let blk
= cx
.lambda1(trait_span
, call
, blkarg
);
276 let ret
= cx
.expr_method_call(
279 cx
.ident_of("emit_enum", trait_span
),
280 vec
![cx
.expr_str(trait_span
, substr
.type_ident
.name
), blk
],
282 cx
.expr_block(cx
.block(trait_span
, vec
![me
, cx
.stmt_expr(ret
)]))
285 _
=> cx
.bug("expected Struct or EnumMatching in derive(Encodable)"),