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.
11 //! The compiler code necessary for `#[deriving(Decodable)]`. See encodable.rs for more.
14 use ast::{MetaItem, Item, Expr, MutMutable};
16 use ext::base::ExtCtxt;
17 use ext::build::AstBuilder;
18 use ext::deriving::generic::*;
19 use ext::deriving::generic::ty::*;
20 use parse::token::InternedString;
24 pub fn expand_deriving_rustc_decodable<F>(cx: &mut ExtCtxt,
31 expand_deriving_decodable_imp(cx, span, mitem, item, push, "rustc_serialize")
34 pub fn expand_deriving_decodable<F>(cx: &mut ExtCtxt,
41 expand_deriving_decodable_imp(cx, span, mitem, item, push, "serialize")
44 fn expand_deriving_decodable_imp<F>(cx: &mut ExtCtxt,
49 krate: &'static str) where
52 let trait_def = TraitDef {
54 attributes: Vec::new(),
55 path: Path::new_(vec!(krate, "Decodable"), None,
56 vec!(box Literal(Path::new_local("__D")),
57 box Literal(Path::new_local("__E"))), true),
58 additional_bounds: Vec::new(),
59 generics: LifetimeBounds {
60 lifetimes: Vec::new(),
61 bounds: vec!(("__D", vec!(Path::new_(
62 vec!(krate, "Decoder"), None,
63 vec!(box Literal(Path::new_local("__E"))), true))),
69 generics: LifetimeBounds::empty(),
71 args: vec!(Ptr(box Literal(Path::new_local("__D")),
72 Borrowed(None, MutMutable))),
73 ret_ty: Literal(Path::new_(vec!("std", "result", "Result"), None,
75 box Literal(Path::new_local("__E"))), true)),
76 attributes: Vec::new(),
77 combine_substructure: combine_substructure(|a, b, c| {
78 decodable_substructure(a, b, c, krate)
83 trait_def.expand(cx, mitem, item, push)
86 fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
87 substr: &Substructure,
88 krate: &str) -> P<Expr> {
89 let decoder = substr.nonself_args[0].clone();
90 let recurse = vec!(cx.ident_of(krate),
91 cx.ident_of("Decodable"),
92 cx.ident_of("decode"));
93 // throw an underscore in front to suppress unused variable warnings
94 let blkarg = cx.ident_of("_d");
95 let blkdecoder = cx.expr_ident(trait_span, blkarg);
96 let calldecode = cx.expr_call_global(trait_span, recurse, vec!(blkdecoder.clone()));
97 let lambdadecode = cx.lambda_expr_1(trait_span, calldecode, blkarg);
99 return match *substr.fields {
100 StaticStruct(_, ref summary) => {
101 let nfields = match *summary {
102 Unnamed(ref fields) => fields.len(),
103 Named(ref fields) => fields.len()
105 let read_struct_field = cx.ident_of("read_struct_field");
107 let path = cx.path_ident(trait_span, substr.type_ident);
108 let result = decode_static_fields(cx,
112 |cx, span, name, field| {
114 cx.expr_method_call(span, blkdecoder.clone(), read_struct_field,
115 vec!(cx.expr_str(span, name),
116 cx.expr_uint(span, field),
117 lambdadecode.clone())))
119 let result = cx.expr_ok(trait_span, result);
120 cx.expr_method_call(trait_span,
122 cx.ident_of("read_struct"),
124 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
125 cx.expr_uint(trait_span, nfields),
126 cx.lambda_expr_1(trait_span, result, blkarg)
129 StaticEnum(_, ref fields) => {
130 let variant = cx.ident_of("i");
132 let mut arms = Vec::new();
133 let mut variants = Vec::new();
134 let rvariant_arg = cx.ident_of("read_enum_variant_arg");
136 for (i, &(name, v_span, ref parts)) in fields.iter().enumerate() {
137 variants.push(cx.expr_str(v_span, token::get_ident(name)));
139 let path = cx.path(trait_span, vec![substr.type_ident, name]);
140 let decoded = decode_static_fields(cx,
144 |cx, span, _, field| {
145 let idx = cx.expr_uint(span, field);
147 cx.expr_method_call(span, blkdecoder.clone(), rvariant_arg,
148 vec!(idx, lambdadecode.clone())))
151 arms.push(cx.arm(v_span,
152 vec!(cx.pat_lit(v_span, cx.expr_uint(v_span, i))),
156 arms.push(cx.arm_unreachable(trait_span));
158 let result = cx.expr_ok(trait_span,
159 cx.expr_match(trait_span,
160 cx.expr_ident(trait_span, variant), arms));
161 let lambda = cx.lambda_expr(trait_span, vec!(blkarg, variant), result);
162 let variant_vec = cx.expr_vec(trait_span, variants);
163 let variant_vec = cx.expr_addr_of(trait_span, variant_vec);
164 let result = cx.expr_method_call(trait_span, blkdecoder,
165 cx.ident_of("read_enum_variant"),
166 vec!(variant_vec, lambda));
167 cx.expr_method_call(trait_span,
169 cx.ident_of("read_enum"),
171 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
172 cx.lambda_expr_1(trait_span, result, blkarg)
175 _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Decodable)")
179 /// Create a decoder for a single enum variant/struct:
180 /// - `outer_pat_path` is the path to this enum variant/struct
181 /// - `getarg` should retrieve the `uint`-th field with name `@str`.
182 fn decode_static_fields<F>(cx: &mut ExtCtxt,
184 outer_pat_path: ast::Path,
185 fields: &StaticFields,
188 F: FnMut(&mut ExtCtxt, Span, InternedString, uint) -> P<Expr>,
191 Unnamed(ref fields) => {
192 let path_expr = cx.expr_path(outer_pat_path);
193 if fields.is_empty() {
196 let fields = fields.iter().enumerate().map(|(i, &span)| {
198 token::intern_and_get_ident(format!("_field{}",
203 cx.expr_call(trait_span, path_expr, fields)
206 Named(ref fields) => {
207 // use the field's span to get nicer error messages.
208 let fields = fields.iter().enumerate().map(|(i, &(name, span))| {
209 let arg = getarg(cx, span, token::get_ident(name), i);
210 cx.field_imm(span, name, arg)
212 cx.expr_struct(trait_span, outer_pat_path, fields)