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:
20 #[deriving(Encodable, Decodable)]
21 struct Node {id: uint}
23 would generate two implementations like:
25 impl<S:serialize::Encoder> Encodable<S> for Node {
26 fn encode(&self, s: &S) {
27 s.emit_struct("Node", 1, || {
28 s.emit_field("id", 0, || s.emit_uint(self.id))
33 impl<D:Decoder> Decodable for node_id {
34 fn decode(d: &D) -> Node {
35 d.read_struct("Node", 1, || {
37 id: d.read_field(~"x", 0, || decode(d))
43 Other interesting scenarios are whe the item has type parameters or
44 references other non-built-in types. A type definition like:
46 #[deriving(Encodable, Decodable)]
47 struct spanned<T> {node: T, span: Span}
49 would yield functions like:
54 > spanned<T>: Encodable<S> {
55 fn encode<S:Encoder>(s: &S) {
57 s.emit_field("node", 0, || self.node.encode(s));
58 s.emit_field("span", 1, || self.span.encode(s));
66 > spanned<T>: Decodable<D> {
67 fn decode(d: &D) -> spanned<T> {
70 node: d.read_field(~"node", 0, || decode(d)),
71 span: d.read_field(~"span", 1, || decode(d)),
78 use ast::{MetaItem, Item, Expr, MutMutable};
80 use ext::base::ExtCtxt;
81 use ext::build::AstBuilder;
82 use ext::deriving::generic::*;
85 pub fn expand_deriving_encodable(cx: &mut ExtCtxt,
88 in_items: ~[@Item]) -> ~[@Item] {
89 let trait_def = TraitDef {
91 path: Path::new_(~["serialize", "Encodable"], None,
92 ~[~Literal(Path::new_local("__E"))], true),
93 additional_bounds: ~[],
94 generics: LifetimeBounds {
96 bounds: ~[("__E", ~[Path::new(~["serialize", "Encoder"])])],
101 generics: LifetimeBounds::empty(),
102 explicit_self: borrowed_explicit_self(),
103 args: ~[Ptr(~Literal(Path::new_local("__E")),
104 Borrowed(None, MutMutable))],
107 const_nonmatching: true,
108 combine_substructure: encodable_substructure,
113 trait_def.expand(cx, mitem, in_items)
116 fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
117 substr: &Substructure) -> @Expr {
118 let encoder = substr.nonself_args[0];
119 // throw an underscore in front to suppress unused variable warnings
120 let blkarg = cx.ident_of("_e");
121 let blkencoder = cx.expr_ident(trait_span, blkarg);
122 let encode = cx.ident_of("encode");
124 return match *substr.fields {
125 Struct(ref fields) => {
126 let emit_struct_field = cx.ident_of("emit_struct_field");
133 }) in fields.iter().enumerate() {
134 let name = match name {
135 Some(id) => token::get_ident(id),
137 token::intern_and_get_ident(format!("_field{}", i))
140 let enc = cx.expr_method_call(span, self_, encode, ~[blkencoder]);
141 let lambda = cx.lambda_expr_1(span, enc, blkarg);
142 let call = cx.expr_method_call(span, blkencoder,
144 ~[cx.expr_str(span, name),
145 cx.expr_uint(span, i),
147 stmts.push(cx.stmt_expr(call));
150 let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg);
151 cx.expr_method_call(trait_span,
153 cx.ident_of("emit_struct"),
155 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
156 cx.expr_uint(trait_span, fields.len()),
161 EnumMatching(idx, variant, ref fields) => {
162 // We're not generating an AST that the borrow checker is expecting,
163 // so we need to generate a unique local variable to take the
164 // mutable loan out on, otherwise we get conflicts which don't
166 let me = cx.stmt_let(trait_span, false, blkarg, encoder);
167 let encoder = cx.expr_ident(trait_span, blkarg);
168 let emit_variant_arg = cx.ident_of("emit_enum_variant_arg");
170 for (i, &FieldInfo { self_, span, .. }) in fields.iter().enumerate() {
171 let enc = cx.expr_method_call(span, self_, encode, ~[blkencoder]);
172 let lambda = cx.lambda_expr_1(span, enc, blkarg);
173 let call = cx.expr_method_call(span, blkencoder,
175 ~[cx.expr_uint(span, i),
177 stmts.push(cx.stmt_expr(call));
180 let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg);
181 let name = cx.expr_str(trait_span, token::get_ident(variant.node.name));
182 let call = cx.expr_method_call(trait_span, blkencoder,
183 cx.ident_of("emit_enum_variant"),
185 cx.expr_uint(trait_span, idx),
186 cx.expr_uint(trait_span, fields.len()),
188 let blk = cx.lambda_expr_1(trait_span, call, blkarg);
189 let ret = cx.expr_method_call(trait_span,
191 cx.ident_of("emit_enum"),
193 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
196 cx.expr_block(cx.block(trait_span, ~[me], Some(ret)))
199 _ => cx.bug("expected Struct or EnumMatching in deriving(Encodable)")