blob: 092738ab8a03d372333f6272ae608e775cc9d617 [file] [log] [blame]
Erick Tryzelaar58415642013-04-10 23:31:511// 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
Jorge Aparicio351409a2015-01-04 03:54:1811//! The compiler code necessary to implement the `#[derive(Encodable)]`
Corey Richardson4989a562014-06-09 20:12:3012//! (and `Decodable`, in decodable.rs) extension. The idea here is that
Jorge Aparicio351409a2015-01-04 03:54:1813//! type-defining items may be tagged with `#[derive(Encodable, Decodable)]`.
Corey Richardson4989a562014-06-09 20:12:3014//!
15//! For example, a type like:
16//!
17//! ```ignore
Jorge Aparicio351409a2015-01-04 03:54:1818//! #[derive(Encodable, Decodable)]
Paul Colliera32249d2015-01-17 23:33:0519//! struct Node { id: usize }
Corey Richardson4989a562014-06-09 20:12:3020//! ```
21//!
22//! would generate two implementations like:
23//!
24//! ```ignore
Barosl Lee94169352014-11-14 08:14:4425//! impl<S: Encoder<E>, E> Encodable<S, E> for Node {
26//! fn encode(&self, s: &mut S) -> Result<(), E> {
27//! s.emit_struct("Node", 1, |this| {
28//! this.emit_struct_field("id", 0, |this| {
29//! Encodable::encode(&self.id, this)
Paul Collierd5c83652015-01-17 23:49:0830//! /* this.emit_usize(self.id) can also be used */
Barosl Lee94169352014-11-14 08:14:4431//! })
Corey Richardson4989a562014-06-09 20:12:3032//! })
33//! }
34//! }
35//!
Barosl Lee94169352014-11-14 08:14:4436//! impl<D: Decoder<E>, E> Decodable<D, E> for Node {
37//! fn decode(d: &mut D) -> Result<Node, E> {
38//! d.read_struct("Node", 1, |this| {
39//! match this.read_struct_field("id", 0, |this| Decodable::decode(this)) {
40//! Ok(id) => Ok(Node { id: id }),
41//! Err(e) => Err(e),
Corey Richardson4989a562014-06-09 20:12:3042//! }
43//! })
44//! }
45//! }
46//! ```
47//!
Joseph Crailad06dfe2014-08-01 23:40:2148//! Other interesting scenarios are when the item has type parameters or
Corey Richardson4989a562014-06-09 20:12:3049//! references other non-built-in types. A type definition like:
50//!
51//! ```ignore
Jorge Aparicio351409a2015-01-04 03:54:1852//! #[derive(Encodable, Decodable)]
Barosl Lee94169352014-11-14 08:14:4453//! struct Spanned<T> { node: T, span: Span }
Corey Richardson4989a562014-06-09 20:12:3054//! ```
55//!
56//! would yield functions like:
57//!
58//! ```ignore
Barosl Lee94169352014-11-14 08:14:4459//! impl<
60//! S: Encoder<E>,
61//! E,
62//! T: Encodable<S, E>
63//! > Encodable<S, E> for Spanned<T> {
64//! fn encode(&self, s: &mut S) -> Result<(), E> {
65//! s.emit_struct("Spanned", 2, |this| {
66//! this.emit_struct_field("node", 0, |this| self.node.encode(this))
Oliver Schneiderb4a1e592015-03-20 07:19:1367//! .unwrap();
Barosl Lee94169352014-11-14 08:14:4468//! this.emit_struct_field("span", 1, |this| self.span.encode(this))
69//! })
Corey Richardson4989a562014-06-09 20:12:3070//! }
Barosl Lee94169352014-11-14 08:14:4471//! }
Corey Richardson4989a562014-06-09 20:12:3072//!
Barosl Lee94169352014-11-14 08:14:4473//! impl<
74//! D: Decoder<E>,
75//! E,
76//! T: Decodable<D, E>
77//! > Decodable<D, E> for Spanned<T> {
78//! fn decode(d: &mut D) -> Result<Spanned<T>, E> {
79//! d.read_struct("Spanned", 2, |this| {
80//! Ok(Spanned {
81//! node: this.read_struct_field("node", 0, |this| Decodable::decode(this))
Oliver Schneiderb4a1e592015-03-20 07:19:1382//! .unwrap(),
Barosl Lee94169352014-11-14 08:14:4483//! span: this.read_struct_field("span", 1, |this| Decodable::decode(this))
Oliver Schneiderb4a1e592015-03-20 07:19:1384//! .unwrap(),
Corey Richardson4989a562014-06-09 20:12:3085//! })
Barosl Lee94169352014-11-14 08:14:4486//! })
Corey Richardson4989a562014-06-09 20:12:3087//! }
Barosl Lee94169352014-11-14 08:14:4488//! }
Corey Richardson4989a562014-06-09 20:12:3089//! ```
Huon Wilson5dc5efe2013-05-15 22:55:5790
Alex Burka83553892016-03-08 18:24:2891use deriving;
Seo Sanghyeonf9ba1072015-12-10 14:23:1492use deriving::generic::*;
93use deriving::generic::ty::*;
94
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:0695use syntax::ast::{Expr, ExprKind, MetaItem, Mutability};
96use syntax::ext::base::{Annotatable, ExtCtxt};
Seo Sanghyeonf9ba1072015-12-10 14:23:1497use syntax::ext::build::AstBuilder;
Seo Sanghyeonf9ba1072015-12-10 14:23:1498use syntax::ptr::P;
Jeffrey Seyfriede85a0d72016-11-16 10:52:3799use syntax::symbol::Symbol;
Jonathan Turner6ae350212016-06-21 22:08:13100use syntax_pos::Span;
Alex Crichton53ad4262014-05-16 07:16:13101
Erick Tryzelaar9edc7de2015-03-27 01:07:49102pub fn expand_deriving_rustc_encodable(cx: &mut ExtCtxt,
103 span: Span,
104 mitem: &MetaItem,
Manish Goregaokar6bc5a922015-05-22 15:40:14105 item: &Annotatable,
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06106 push: &mut FnMut(Annotatable)) {
Alex Crichtona76a8022014-12-19 06:52:48107 expand_deriving_encodable_imp(cx, span, mitem, item, push, "rustc_serialize")
108}
109
Erick Tryzelaar9edc7de2015-03-27 01:07:49110pub fn expand_deriving_encodable(cx: &mut ExtCtxt,
111 span: Span,
112 mitem: &MetaItem,
Manish Goregaokar6bc5a922015-05-22 15:40:14113 item: &Annotatable,
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06114 push: &mut FnMut(Annotatable)) {
Alex Crichtona76a8022014-12-19 06:52:48115 expand_deriving_encodable_imp(cx, span, mitem, item, push, "serialize")
116}
117
Erick Tryzelaar9edc7de2015-03-27 01:07:49118fn expand_deriving_encodable_imp(cx: &mut ExtCtxt,
119 span: Span,
120 mitem: &MetaItem,
Manish Goregaokar6bc5a922015-05-22 15:40:14121 item: &Annotatable,
Nick Cameronc0a42ae2015-04-28 05:34:39122 push: &mut FnMut(Annotatable),
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06123 krate: &'static str) {
Alex Crichton5cccf3c2015-07-30 00:01:14124 if cx.crate_root != Some("std") {
Keegan McAllister67350bc2014-09-07 21:57:26125 // FIXME(#21880): lift this requirement.
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06126 cx.span_err(span,
127 "this trait cannot be derived with #![no_std] \
Alex Crichton5cccf3c2015-07-30 00:01:14128 or #![no_core]");
Keegan McAllister67350bc2014-09-07 21:57:26129 return;
130 }
131
Alex Burka83553892016-03-08 18:24:28132 let typaram = &*deriving::hygienic_type_parameter(item, "__S");
133
Alex Crichtona25c7042013-05-30 21:58:16134 let trait_def = TraitDef {
Niko Matsakiseb774f62014-02-09 00:39:53135 span: span,
Patrick Walton58fd6ab92014-02-28 21:09:09136 attributes: Vec::new(),
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06137 path: Path::new_(vec![krate, "Encodable"], None, vec![], true),
Patrick Walton58fd6ab92014-02-28 21:09:09138 additional_bounds: Vec::new(),
Alex Crichton0cb7a402015-01-04 06:24:50139 generics: LifetimeBounds::empty(),
Michael Layzell38d450f2015-08-29 18:50:05140 is_unsafe: false,
Jeffrey Seyfried02f081c2016-08-29 11:14:25141 supports_unions: false,
iirelue593c3b2016-10-29 21:54:04142 methods: vec![
Alex Crichtona25c7042013-05-30 21:58:16143 MethodDef {
144 name: "encode",
Alex Crichton0cb7a402015-01-04 06:24:50145 generics: LifetimeBounds {
146 lifetimes: Vec::new(),
Alex Burka83553892016-03-08 18:24:28147 bounds: vec![(typaram,
iirelue593c3b2016-10-29 21:54:04148 vec![Path::new_(vec![krate, "Encoder"], None, vec![], true)])]
Alex Crichton0cb7a402015-01-04 06:24:50149 },
Eduard Burtescub2d30b72014-02-06 22:38:33150 explicit_self: borrowed_explicit_self(),
iirelue593c3b2016-10-29 21:54:04151 args: vec![Ptr(Box::new(Literal(Path::new_local(typaram))),
152 Borrowed(None, Mutability::Mutable))],
Alex Crichton0cb7a402015-01-04 06:24:50153 ret_ty: Literal(Path::new_(
Keegan McAllister67350bc2014-09-07 21:57:26154 pathvec_std!(cx, core::result::Result),
Alex Crichton0cb7a402015-01-04 06:24:50155 None,
iirelue593c3b2016-10-29 21:54:04156 vec![Box::new(Tuple(Vec::new())), Box::new(Literal(Path::new_(
Alex Burka83553892016-03-08 18:24:28157 vec![typaram, "Error"], None, vec![], false
iirelue593c3b2016-10-29 21:54:04158 )))],
Alex Crichton0cb7a402015-01-04 06:24:50159 true
160 )),
Edward Wang2cf1e4b2014-04-23 14:43:45161 attributes: Vec::new(),
Manish Goregaokar5b638412015-05-17 05:58:19162 is_unsafe: false,
Björn Steinbrink0eeb14e2016-05-12 15:54:05163 unify_fieldless_variants: false,
Felix S. Klock II0d5bcb12015-02-15 08:52:21164 combine_substructure: combine_substructure(Box::new(|a, b, c| {
Oliver Schneider2fd22102016-04-12 13:41:46165 encodable_substructure(a, b, c, krate)
Felix S. Klock II0d5bcb12015-02-15 08:52:21166 })),
Dzmitry Malyshaue5632152015-01-25 05:29:24167 }
iirelue593c3b2016-10-29 21:54:04168 ],
Dzmitry Malyshaue5632152015-01-25 05:29:24169 associated_types: Vec::new(),
Erick Tryzelaar58415642013-04-10 23:31:51170 };
171
Manish Goregaokar6bc5a922015-05-22 15:40:14172 trait_def.expand(cx, mitem, item, push)
Erick Tryzelaar58415642013-04-10 23:31:51173}
Huon Wilson5dc5efe2013-05-15 22:55:57174
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06175fn encodable_substructure(cx: &mut ExtCtxt,
176 trait_span: Span,
177 substr: &Substructure,
178 krate: &'static str)
179 -> P<Expr> {
Eduard Burtescuccd84982014-09-13 16:06:01180 let encoder = substr.nonself_args[0].clone();
Alex Crichtona25c7042013-05-30 21:58:16181 // throw an underscore in front to suppress unused variable warnings
182 let blkarg = cx.ident_of("_e");
Huon Wilsonb079ebe2014-01-27 04:25:37183 let blkencoder = cx.expr_ident(trait_span, blkarg);
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06184 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")]));
Huon Wilson5dc5efe2013-05-15 22:55:57188
Alex Crichtona25c7042013-05-30 21:58:16189 return match *substr.fields {
Vadim Petrochenkov4e8e6072016-02-22 18:24:32190 Struct(_, ref fields) => {
Alex Crichtona25c7042013-05-30 21:58:16191 let emit_struct_field = cx.ident_of("emit_struct_field");
Patrick Walton58fd6ab92014-02-28 21:09:09192 let mut stmts = Vec::new();
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06193 for (i, &FieldInfo { name, ref self_, span, .. }) in fields.iter().enumerate() {
Huon Wilsonb079ebe2014-01-27 04:25:37194 let name = match name {
Jeffrey Seyfriede85a0d72016-11-16 10:52:37195 Some(id) => id.name,
196 None => Symbol::intern(&format!("_field{}", i)),
Alex Crichtona25c7042013-05-30 21:58:16197 };
Oliver Schneider2fd22102016-04-12 13:41:46198 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()]);
Eduard Burtescu49772fb2016-10-25 23:17:29200 let lambda = cx.lambda1(span, enc, blkarg);
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06201 let call = cx.expr_method_call(span,
202 blkencoder.clone(),
Alex Crichtona25c7042013-05-30 21:58:16203 emit_struct_field,
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06204 vec![cx.expr_str(span, name),
205 cx.expr_usize(span, i),
206 lambda]);
Sean McArthurf1739b12014-03-18 17:58:26207
208 // last call doesn't need a try!
Felix S. Klock IIfaf3bcd2015-02-20 12:10:54209 let last = fields.len() - 1;
Sean McArthurf1739b12014-03-18 17:58:26210 let call = if i != last {
211 cx.expr_try(span, call)
212 } else {
Oliver Schneider80bf9ae2016-02-08 15:05:05213 cx.expr(span, ExprKind::Ret(Some(call)))
Sean McArthurf1739b12014-03-18 17:58:26214 };
Alex Crichtona25c7042013-05-30 21:58:16215 stmts.push(cx.stmt_expr(call));
216 }
Huon Wilson5dc5efe2013-05-15 22:55:57217
Piotr Jawniak1dc13e42014-06-01 12:16:11218 // unit structs have no fields and need to return Ok()
219 if stmts.is_empty() {
Oliver Schneider80bf9ae2016-02-08 15:05:05220 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)));
Piotr Jawniak1dc13e42014-06-01 12:16:11222 stmts.push(cx.stmt_expr(ret_ok));
223 }
224
Huon Wilsonb079ebe2014-01-27 04:25:37225 let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg);
Patrick Walton8e52b852014-01-10 22:02:36226 cx.expr_method_call(trait_span,
227 encoder,
228 cx.ident_of("emit_struct"),
Jeffrey Seyfriede85a0d72016-11-16 10:52:37229 vec![cx.expr_str(trait_span, substr.type_ident.name),
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06230 cx.expr_usize(trait_span, fields.len()),
231 blk])
Huon Wilson5dc5efe2013-05-15 22:55:57232 }
233
Alex Crichtona25c7042013-05-30 21:58:16234 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.
Huon Wilsonb079ebe2014-01-27 04:25:37239 let me = cx.stmt_let(trait_span, false, blkarg, encoder);
240 let encoder = cx.expr_ident(trait_span, blkarg);
Alex Crichtona25c7042013-05-30 21:58:16241 let emit_variant_arg = cx.ident_of("emit_enum_variant_arg");
Patrick Walton58fd6ab92014-02-28 21:09:09242 let mut stmts = Vec::new();
Tamir Duberstein10f15e72015-03-24 23:54:09243 if !fields.is_empty() {
James Miller1246d402015-01-09 03:10:57244 let last = fields.len() - 1;
245 for (i, &FieldInfo { ref self_, span, .. }) in fields.iter().enumerate() {
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06246 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()]);
Eduard Burtescu49772fb2016-10-25 23:17:29249 let lambda = cx.lambda1(span, enc, blkarg);
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06250 let call = cx.expr_method_call(span,
251 blkencoder.clone(),
James Miller1246d402015-01-09 03:10:57252 emit_variant_arg,
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06253 vec![cx.expr_usize(span, i), lambda]);
James Miller1246d402015-01-09 03:10:57254 let call = if i != last {
255 cx.expr_try(span, call)
256 } else {
Oliver Schneider80bf9ae2016-02-08 15:05:05257 cx.expr(span, ExprKind::Ret(Some(call)))
James Miller1246d402015-01-09 03:10:57258 };
259 stmts.push(cx.stmt_expr(call));
260 }
261 } else {
Oliver Schneider80bf9ae2016-02-08 15:05:05262 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)));
Sean McArthurf1739b12014-03-18 17:58:26264 stmts.push(cx.stmt_expr(ret_ok));
265 }
266
Huon Wilsonb079ebe2014-01-27 04:25:37267 let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg);
Jeffrey Seyfriede85a0d72016-11-16 10:52:37268 let name = cx.expr_str(trait_span, variant.node.name.name);
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06269 let call = cx.expr_method_call(trait_span,
270 blkencoder,
Alex Crichtona25c7042013-05-30 21:58:16271 cx.ident_of("emit_enum_variant"),
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06272 vec![name,
273 cx.expr_usize(trait_span, idx),
274 cx.expr_usize(trait_span, fields.len()),
275 blk]);
Eduard Burtescu49772fb2016-10-25 23:17:29276 let blk = cx.lambda1(trait_span, call, blkarg);
Patrick Walton8e52b852014-01-10 22:02:36277 let ret = cx.expr_method_call(trait_span,
278 encoder,
Alex Crichtona25c7042013-05-30 21:58:16279 cx.ident_of("emit_enum"),
Jeffrey Seyfriede85a0d72016-11-16 10:52:37280 vec![cx.expr_str(trait_span ,substr.type_ident.name),
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06281 blk]);
Jeffrey Seyfriedb7da35a2016-06-23 09:51:18282 cx.expr_block(cx.block(trait_span, vec![me, cx.stmt_expr(ret)]))
Huon Wilson5dc5efe2013-05-15 22:55:57283 }
284
Srinivas Reddy Thatiparthy9652fcb2016-07-19 17:32:06285 _ => cx.bug("expected Struct or EnumMatching in derive(Encodable)"),
Alex Crichtona25c7042013-05-30 21:58:16286 };
Huon Wilson5dc5efe2013-05-15 22:55:57287}