1 // 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.
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.
13 The compiler code necessary to implement the #[deriving(Encodable)]
14 (and Decodable, in decodable.rs) extension. The idea here is that
15 type-defining items may be tagged with #[deriving(Encodable,
18 For example, a type like:
21 #[deriving(Encodable, Decodable)]
22 struct Node {id: uint}
25 would generate two implementations like:
27 impl<S:serialize::Encoder> Encodable<S> for Node {
28 fn encode(&self, s: &S) {
29 s.emit_struct("Node", 1, || {
30 s.emit_field("id", 0, || s.emit_uint(self.id))
35 impl<D:Decoder> Decodable for node_id {
36 fn decode(d: &D) -> Node {
37 d.read_struct("Node", 1, || {
39 id: d.read_field(~"x", 0, || decode(d))
45 Other interesting scenarios are whe the item has type parameters or
46 references other non-built-in types. A type definition like:
49 #[deriving(Encodable, Decodable)]
50 struct spanned<T> {node: T, span: Span}
53 would yield functions like:
59 > spanned<T>: Encodable<S> {
60 fn encode<S:Encoder>(s: &S) {
62 s.emit_field("node", 0, || self.node.encode(s));
63 s.emit_field("span", 1, || self.span.encode(s));
71 > spanned<T>: Decodable<D> {
72 fn decode(d: &D) -> spanned<T> {
75 node: d.read_field(~"node", 0, || decode(d)),
76 span: d.read_field(~"span", 1, || decode(d)),
84 use ast::{MetaItem, Item, Expr, MutMutable};
86 use ext::base::ExtCtxt;
87 use ext::build::AstBuilder;
88 use ext::deriving::generic::*;
91 pub fn expand_deriving_encodable(cx: &mut ExtCtxt,
96 let trait_def = TraitDef {
98 path: Path::new_(~["serialize", "Encodable"], None,
99 ~[~Literal(Path::new_local("__E"))], true),
100 additional_bounds: ~[],
101 generics: LifetimeBounds {
103 bounds: ~[("__E", ~[Path::new(~["serialize", "Encoder"])])],
108 generics: LifetimeBounds::empty(),
109 explicit_self: borrowed_explicit_self(),
110 args: ~[Ptr(~Literal(Path::new_local("__E")),
111 Borrowed(None, MutMutable))],
114 const_nonmatching: true,
115 combine_substructure: encodable_substructure,
120 trait_def.expand(cx, mitem, item, push)
123 fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
124 substr: &Substructure) -> @Expr {
125 let encoder = substr.nonself_args[0];
126 // throw an underscore in front to suppress unused variable warnings
127 let blkarg = cx.ident_of("_e");
128 let blkencoder = cx.expr_ident(trait_span, blkarg);
129 let encode = cx.ident_of("encode");
131 return match *substr.fields {
132 Struct(ref fields) => {
133 let emit_struct_field = cx.ident_of("emit_struct_field");
140 }) in fields.iter().enumerate() {
141 let name = match name {
142 Some(id) => token::get_ident(id),
144 token::intern_and_get_ident(format!("_field{}", i))
147 let enc = cx.expr_method_call(span, self_, encode, ~[blkencoder]);
148 let lambda = cx.lambda_expr_1(span, enc, blkarg);
149 let call = cx.expr_method_call(span, blkencoder,
151 ~[cx.expr_str(span, name),
152 cx.expr_uint(span, i),
154 stmts.push(cx.stmt_expr(call));
157 let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg);
158 cx.expr_method_call(trait_span,
160 cx.ident_of("emit_struct"),
162 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
163 cx.expr_uint(trait_span, fields.len()),
168 EnumMatching(idx, variant, ref fields) => {
169 // We're not generating an AST that the borrow checker is expecting,
170 // so we need to generate a unique local variable to take the
171 // mutable loan out on, otherwise we get conflicts which don't
173 let me = cx.stmt_let(trait_span, false, blkarg, encoder);
174 let encoder = cx.expr_ident(trait_span, blkarg);
175 let emit_variant_arg = cx.ident_of("emit_enum_variant_arg");
177 for (i, &FieldInfo { self_, span, .. }) in fields.iter().enumerate() {
178 let enc = cx.expr_method_call(span, self_, encode, ~[blkencoder]);
179 let lambda = cx.lambda_expr_1(span, enc, blkarg);
180 let call = cx.expr_method_call(span, blkencoder,
182 ~[cx.expr_uint(span, i),
184 stmts.push(cx.stmt_expr(call));
187 let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg);
188 let name = cx.expr_str(trait_span, token::get_ident(variant.node.name));
189 let call = cx.expr_method_call(trait_span, blkencoder,
190 cx.ident_of("emit_enum_variant"),
192 cx.expr_uint(trait_span, idx),
193 cx.expr_uint(trait_span, fields.len()),
195 let blk = cx.lambda_expr_1(trait_span, call, blkarg);
196 let ret = cx.expr_method_call(trait_span,
198 cx.ident_of("emit_enum"),
200 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
203 cx.expr_block(cx.block(trait_span, ~[me], Some(ret)))
206 _ => cx.bug("expected Struct or EnumMatching in deriving(Encodable)")