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)
85 trait_def.expand(cx, mitem, item, push)
88 fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
89 substr: &Substructure,
90 krate: &str) -> P<Expr> {
91 let decoder = substr.nonself_args[0].clone();
92 let recurse = vec!(cx.ident_of(krate),
93 cx.ident_of("Decodable"),
94 cx.ident_of("decode"));
95 let exprdecode = cx.expr_path(cx.path_global(trait_span, recurse));
96 // throw an underscore in front to suppress unused variable warnings
97 let blkarg = cx.ident_of("_d");
98 let blkdecoder = cx.expr_ident(trait_span, blkarg);
100 return match *substr.fields {
101 StaticStruct(_, ref summary) => {
102 let nfields = match *summary {
103 Unnamed(ref fields) => fields.len(),
104 Named(ref fields) => fields.len()
106 let read_struct_field = cx.ident_of("read_struct_field");
108 let path = cx.path_ident(trait_span, substr.type_ident);
109 let result = decode_static_fields(cx,
113 |cx, span, name, field| {
115 cx.expr_method_call(span, blkdecoder.clone(), read_struct_field,
116 vec!(cx.expr_str(span, name),
117 cx.expr_usize(span, field),
118 exprdecode.clone())))
120 let result = cx.expr_ok(trait_span, result);
121 cx.expr_method_call(trait_span,
123 cx.ident_of("read_struct"),
125 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
126 cx.expr_usize(trait_span, nfields),
127 cx.lambda_expr_1(trait_span, result, blkarg)
130 StaticEnum(_, ref fields) => {
131 let variant = cx.ident_of("i");
133 let mut arms = Vec::new();
134 let mut variants = Vec::new();
135 let rvariant_arg = cx.ident_of("read_enum_variant_arg");
137 for (i, &(name, v_span, ref parts)) in fields.iter().enumerate() {
138 variants.push(cx.expr_str(v_span, token::get_ident(name)));
140 let path = cx.path(trait_span, vec![substr.type_ident, name]);
141 let decoded = decode_static_fields(cx,
145 |cx, span, _, field| {
146 let idx = cx.expr_usize(span, field);
148 cx.expr_method_call(span, blkdecoder.clone(), rvariant_arg,
149 vec!(idx, exprdecode.clone())))
152 arms.push(cx.arm(v_span,
153 vec!(cx.pat_lit(v_span, cx.expr_usize(v_span, i))),
157 arms.push(cx.arm_unreachable(trait_span));
159 let result = cx.expr_ok(trait_span,
160 cx.expr_match(trait_span,
161 cx.expr_ident(trait_span, variant), arms));
162 let lambda = cx.lambda_expr(trait_span, vec!(blkarg, variant), result);
163 let variant_vec = cx.expr_vec(trait_span, variants);
164 let variant_vec = cx.expr_addr_of(trait_span, variant_vec);
165 let result = cx.expr_method_call(trait_span, blkdecoder,
166 cx.ident_of("read_enum_variant"),
167 vec!(variant_vec, lambda));
168 cx.expr_method_call(trait_span,
170 cx.ident_of("read_enum"),
172 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
173 cx.lambda_expr_1(trait_span, result, blkarg)
176 _ => cx.bug("expected StaticEnum or StaticStruct in derive(Decodable)")
180 /// Create a decoder for a single enum variant/struct:
181 /// - `outer_pat_path` is the path to this enum variant/struct
182 /// - `getarg` should retrieve the `usize`-th field with name `@str`.
183 fn decode_static_fields<F>(cx: &mut ExtCtxt,
185 outer_pat_path: ast::Path,
186 fields: &StaticFields,
189 F: FnMut(&mut ExtCtxt, Span, InternedString, usize) -> P<Expr>,
192 Unnamed(ref fields) => {
193 let path_expr = cx.expr_path(outer_pat_path);
194 if fields.is_empty() {
197 let fields = fields.iter().enumerate().map(|(i, &span)| {
199 token::intern_and_get_ident(&format!("_field{}", i)[]),
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)