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
::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}
;
98 pub fn expand_deriving_rustc_encodable(
103 push
: &mut dyn FnMut(Annotatable
),
105 let krate
= sym
::rustc_serialize
;
106 let typaram
= sym
::__S
;
108 let trait_def
= TraitDef
{
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(),
115 supports_unions
: false,
116 methods
: vec
![MethodDef
{
121 vec
![Path
::new_(vec
![krate
, sym
::Encoder
], None
, vec
![], PathKind
::Global
)],
124 explicit_self
: borrowed_explicit_self(),
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.
134 ret_ty
: Literal(Path
::new_(
135 pathvec_std
!(result
::Result
),
138 Box
::new(Tuple(Vec
::new())),
139 Box
::new(Literal(Path
::new_(
140 vec
![typaram
, sym
::Error
],
148 attributes
: Vec
::new(),
150 unify_fieldless_variants
: false,
151 combine_substructure
: combine_substructure(Box
::new(|a
, b
, c
| {
152 encodable_substructure(a
, b
, c
, krate
)
155 associated_types
: Vec
::new(),
158 trait_def
.expand(cx
, mitem
, item
, push
)
161 fn encodable_substructure(
162 cx
: &mut ExtCtxt
<'_
>,
164 substr
: &Substructure
<'_
>,
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(
174 Ident
::new(krate
, trait_span
),
175 Ident
::new(sym
::Encodable
, trait_span
),
176 Ident
::new(sym
::encode
, trait_span
),
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
{
187 None
=> Symbol
::intern(&format
!("_field{}", i
)),
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(
196 vec
![cx
.expr_str(span
, name
), cx
.expr_usize(span
, i
), lambda
],
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
)
204 cx
.expr(span
, ExprKind
::Ret(Some(call
)))
207 let stmt
= cx
.stmt_expr(call
);
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
)
216 cx
.lambda_stmts_1(trait_span
, stmts
, blkarg
)
222 Ident
::new(sym
::emit_struct
, trait_span
),
224 cx
.expr_str(trait_span
, substr
.type_ident
.name
),
225 cx
.expr_usize(trait_span
, fields
.len()),
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
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());
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(
251 vec
![cx
.expr_usize(span
, i
), lambda
],
253 let call
= if i
!= last
{
254 cx
.expr_try(span
, call
)
256 cx
.expr(span
, ExprKind
::Ret(Some(call
)))
258 stmts
.push(cx
.stmt_expr(call
));
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
));
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(
271 Ident
::new(sym
::emit_enum_variant
, trait_span
),
274 cx
.expr_usize(trait_span
, idx
),
275 cx
.expr_usize(trait_span
, fields
.len()),
279 let blk
= cx
.lambda1(trait_span
, call
, blkarg
);
280 let ret
= cx
.expr_method_call(
283 Ident
::new(sym
::emit_enum
, trait_span
),
284 vec
![cx
.expr_str(trait_span
, substr
.type_ident
.name
), blk
],
286 cx
.expr_block(cx
.block(trait_span
, vec
![me
, cx
.stmt_expr(ret
)]))
289 _
=> cx
.bug("expected Struct or EnumMatching in derive(Encodable)"),