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.
12 The compiler code necessary for `#[deriving(Decodable)]`. See
13 encodable.rs for more.
17 use ast::{MetaItem, Item, Expr, MutMutable, Ident};
19 use ext::base::ExtCtxt;
20 use ext::build::AstBuilder;
21 use ext::deriving::generic::*;
22 use parse::token::InternedString;
25 pub fn expand_deriving_decodable(cx: &mut ExtCtxt,
30 let trait_def = TraitDef {
32 attributes: Vec::new(),
33 path: Path::new_(vec!("serialize", "Decodable"), None,
34 vec!(~Literal(Path::new_local("__D")),
35 ~Literal(Path::new_local("__E"))), true),
36 additional_bounds: Vec::new(),
37 generics: LifetimeBounds {
38 lifetimes: Vec::new(),
39 bounds: vec!(("__D", ast::StaticSize, vec!(Path::new_(
40 vec!("serialize", "Decoder"), None,
41 vec!(~Literal(Path::new_local("__E"))), true))),
42 ("__E", ast::StaticSize, vec!()))
47 generics: LifetimeBounds::empty(),
49 args: vec!(Ptr(~Literal(Path::new_local("__D")),
50 Borrowed(None, MutMutable))),
51 ret_ty: Literal(Path::new_(vec!("std", "result", "Result"), None,
52 vec!(~Self, ~Literal(Path::new_local("__E"))), true)),
53 attributes: Vec::new(),
54 const_nonmatching: true,
55 combine_substructure: combine_substructure(|a, b, c| {
56 decodable_substructure(a, b, c)
61 trait_def.expand(cx, mitem, item, push)
64 fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
65 substr: &Substructure) -> @Expr {
66 let decoder = substr.nonself_args[0];
67 let recurse = vec!(cx.ident_of("serialize"),
68 cx.ident_of("Decodable"),
69 cx.ident_of("decode"));
70 // throw an underscore in front to suppress unused variable warnings
71 let blkarg = cx.ident_of("_d");
72 let blkdecoder = cx.expr_ident(trait_span, blkarg);
73 let calldecode = cx.expr_call_global(trait_span, recurse, vec!(blkdecoder));
74 let lambdadecode = cx.lambda_expr_1(trait_span, calldecode, blkarg);
76 return match *substr.fields {
77 StaticStruct(_, ref summary) => {
78 let nfields = match *summary {
79 Unnamed(ref fields) => fields.len(),
80 Named(ref fields) => fields.len()
82 let read_struct_field = cx.ident_of("read_struct_field");
84 let result = decode_static_fields(cx,
88 |cx, span, name, field| {
90 cx.expr_method_call(span, blkdecoder, read_struct_field,
91 vec!(cx.expr_str(span, name),
92 cx.expr_uint(span, field),
95 let result = cx.expr_ok(trait_span, result);
96 cx.expr_method_call(trait_span,
98 cx.ident_of("read_struct"),
100 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
101 cx.expr_uint(trait_span, nfields),
102 cx.lambda_expr_1(trait_span, result, blkarg)
105 StaticEnum(_, ref fields) => {
106 let variant = cx.ident_of("i");
108 let mut arms = Vec::new();
109 let mut variants = Vec::new();
110 let rvariant_arg = cx.ident_of("read_enum_variant_arg");
112 for (i, &(name, v_span, ref parts)) in fields.iter().enumerate() {
113 variants.push(cx.expr_str(v_span, token::get_ident(name)));
115 let decoded = decode_static_fields(cx,
119 |cx, span, _, field| {
120 let idx = cx.expr_uint(span, field);
122 cx.expr_method_call(span, blkdecoder, rvariant_arg,
123 vec!(idx, lambdadecode)))
126 arms.push(cx.arm(v_span,
127 vec!(cx.pat_lit(v_span, cx.expr_uint(v_span, i))),
131 arms.push(cx.arm_unreachable(trait_span));
133 let result = cx.expr_ok(trait_span,
134 cx.expr_match(trait_span,
135 cx.expr_ident(trait_span, variant), arms));
136 let lambda = cx.lambda_expr(trait_span, vec!(blkarg, variant), result);
137 let variant_vec = cx.expr_vec(trait_span, variants);
138 let result = cx.expr_method_call(trait_span, blkdecoder,
139 cx.ident_of("read_enum_variant"),
140 vec!(variant_vec, lambda));
141 cx.expr_method_call(trait_span,
143 cx.ident_of("read_enum"),
145 cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
146 cx.lambda_expr_1(trait_span, result, blkarg)
149 _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Decodable)")
153 /// Create a decoder for a single enum variant/struct:
154 /// - `outer_pat_ident` is the name of this enum variant/struct
155 /// - `getarg` should retrieve the `uint`-th field with name `@str`.
156 fn decode_static_fields(cx: &mut ExtCtxt,
158 outer_pat_ident: Ident,
159 fields: &StaticFields,
160 getarg: |&mut ExtCtxt, Span, InternedString, uint| -> @Expr)
163 Unnamed(ref fields) => {
164 if fields.is_empty() {
165 cx.expr_ident(trait_span, outer_pat_ident)
167 let fields = fields.iter().enumerate().map(|(i, &span)| {
169 token::intern_and_get_ident(format!("_field{}",
174 cx.expr_call_ident(trait_span, outer_pat_ident, fields)
177 Named(ref fields) => {
178 // use the field's span to get nicer error messages.
179 let fields = fields.iter().enumerate().map(|(i, &(name, span))| {
180 let arg = getarg(cx, span, token::get_ident(name), i);
181 cx.field_imm(span, name, arg)
183 cx.expr_struct_ident(trait_span, outer_pat_ident, fields)