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 `#[derive(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, vec!(), true),
56 additional_bounds: Vec::new(),
57 generics: LifetimeBounds::empty(),
61 generics: LifetimeBounds {
62 lifetimes: Vec::new(),
63 bounds: vec!(("__D", vec!(Path::new_(
64 vec!(krate, "Decoder"), None,
68 args: vec!(Ptr(box Literal(Path::new_local("__D")),
69 Borrowed(None, MutMutable))),
70 ret_ty: Literal(Path::new_(
71 vec!("std", "result", "Result"),
73 vec!(box Self, box Literal(Path::new_(
74 vec!["__D", "Error"], None, vec![], false
78 attributes: Vec::new(),
79 combine_substructure: combine_substructure(box |a, b, c| {
80 decodable_substructure(a, b, c, krate)
84 associated_types: Vec::new(),
87 trait_def.expand(cx, mitem, item, push)
90 fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
91 substr: &Substructure,
92 krate: &str) -> P<Expr> {
93 let decoder = substr.nonself_args[0].clone();
94 let recurse = vec!(cx.ident_of(krate),
95 cx.ident_of("Decodable"),
96 cx.ident_of("decode"));
97 let exprdecode = cx.expr_path(cx.path_global(trait_span, recurse));
98 // throw an underscore in front to suppress unused variable warnings
99 let blkarg = cx.ident_of("_d");
100 let blkdecoder = cx.expr_ident(trait_span, blkarg);
102 return match *substr.fields {
103 StaticStruct(_, ref summary) => {
104 let nfields = match *summary {
105 Unnamed(ref fields) => fields.len(),
106 Named(ref fields) => fields.len()
108 let read_struct_field = cx.ident_of("read_struct_field");
110 let path = cx.path_ident(trait_span, substr.type_ident);
111 let result = decode_static_fields(cx,
115 |cx, span, name, field| {
117 cx.expr_method_call(span, blkdecoder.clone(), read_struct_field,
118 vec!(cx.expr_str(span, name),
119 cx.expr_usize(span, field),
120 exprdecode.clone())))
122 let result = cx.expr_ok(trait_span, result);
123 cx.expr_method_call(trait_span,
125 cx.ident_of("read_struct"),
127 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
128 cx.expr_usize(trait_span, nfields),
129 cx.lambda_expr_1(trait_span, result, blkarg)
132 StaticEnum(_, ref fields) => {
133 let variant = cx.ident_of("i");
135 let mut arms = Vec::new();
136 let mut variants = Vec::new();
137 let rvariant_arg = cx.ident_of("read_enum_variant_arg");
139 for (i, &(name, v_span, ref parts)) in fields.iter().enumerate() {
140 variants.push(cx.expr_str(v_span, token::get_ident(name)));
142 let path = cx.path(trait_span, vec![substr.type_ident, name]);
143 let decoded = decode_static_fields(cx,
147 |cx, span, _, field| {
148 let idx = cx.expr_usize(span, field);
150 cx.expr_method_call(span, blkdecoder.clone(), rvariant_arg,
151 vec!(idx, exprdecode.clone())))
154 arms.push(cx.arm(v_span,
155 vec!(cx.pat_lit(v_span, cx.expr_usize(v_span, i))),
159 arms.push(cx.arm_unreachable(trait_span));
161 let result = cx.expr_ok(trait_span,
162 cx.expr_match(trait_span,
163 cx.expr_ident(trait_span, variant), arms));
164 let lambda = cx.lambda_expr(trait_span, vec!(blkarg, variant), result);
165 let variant_vec = cx.expr_vec(trait_span, variants);
166 let variant_vec = cx.expr_addr_of(trait_span, variant_vec);
167 let result = cx.expr_method_call(trait_span, blkdecoder,
168 cx.ident_of("read_enum_variant"),
169 vec!(variant_vec, lambda));
170 cx.expr_method_call(trait_span,
172 cx.ident_of("read_enum"),
174 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
175 cx.lambda_expr_1(trait_span, result, blkarg)
178 _ => cx.bug("expected StaticEnum or StaticStruct in derive(Decodable)")
182 /// Create a decoder for a single enum variant/struct:
183 /// - `outer_pat_path` is the path to this enum variant/struct
184 /// - `getarg` should retrieve the `usize`-th field with name `@str`.
185 fn decode_static_fields<F>(cx: &mut ExtCtxt,
187 outer_pat_path: ast::Path,
188 fields: &StaticFields,
191 F: FnMut(&mut ExtCtxt, Span, InternedString, usize) -> P<Expr>,
194 Unnamed(ref fields) => {
195 let path_expr = cx.expr_path(outer_pat_path);
196 if fields.is_empty() {
199 let fields = fields.iter().enumerate().map(|(i, &span)| {
201 token::intern_and_get_ident(&format!("_field{}", i)[]),
205 cx.expr_call(trait_span, path_expr, fields)
208 Named(ref fields) => {
209 // use the field's span to get nicer error messages.
210 let fields = fields.iter().enumerate().map(|(i, &(name, span))| {
211 let arg = getarg(cx, span, token::get_ident(name), i);
212 cx.field_imm(span, name, arg)
214 cx.expr_struct(trait_span, outer_pat_path, fields)