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, Expr, MutMutable}
;
16 use ext
::base
::{ExtCtxt, Annotatable}
;
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(cx
: &mut ExtCtxt
,
28 push
: &mut FnMut(Annotatable
))
30 expand_deriving_decodable_imp(cx
, span
, mitem
, item
, push
, "rustc_serialize")
33 pub fn expand_deriving_decodable(cx
: &mut ExtCtxt
,
37 push
: &mut FnMut(Annotatable
))
39 expand_deriving_decodable_imp(cx
, span
, mitem
, item
, push
, "serialize")
42 fn expand_deriving_decodable_imp(cx
: &mut ExtCtxt
,
46 push
: &mut FnMut(Annotatable
),
50 // FIXME(#21880): lift this requirement.
51 cx
.span_err(span
, "this trait cannot be derived with #![no_std]");
55 let trait_def
= TraitDef
{
57 attributes
: Vec
::new(),
58 path
: Path
::new_(vec
!(krate
, "Decodable"), None
, vec
!(), true),
59 additional_bounds
: Vec
::new(),
60 generics
: LifetimeBounds
::empty(),
64 generics
: LifetimeBounds
{
65 lifetimes
: Vec
::new(),
66 bounds
: vec
!(("__D", vec
!(Path
::new_(
67 vec
!(krate
, "Decoder"), None
,
71 args
: vec
!(Ptr(Box
::new(Literal(Path
::new_local("__D"))),
72 Borrowed(None
, MutMutable
))),
73 ret_ty
: Literal(Path
::new_(
74 pathvec_std
!(cx
, core
::result
::Result
),
76 vec
!(Box
::new(Self_
), Box
::new(Literal(Path
::new_(
77 vec
!["__D", "Error"], None
, vec
![], false
81 attributes
: Vec
::new(),
83 combine_substructure
: combine_substructure(Box
::new(|a
, b
, c
| {
84 decodable_substructure(a
, b
, c
, krate
)
88 associated_types
: Vec
::new(),
91 trait_def
.expand(cx
, mitem
, item
, push
)
94 fn decodable_substructure(cx
: &mut ExtCtxt
, trait_span
: Span
,
95 substr
: &Substructure
,
96 krate
: &str) -> P
<Expr
> {
97 let decoder
= substr
.nonself_args
[0].clone();
98 let recurse
= vec
!(cx
.ident_of(krate
),
99 cx
.ident_of("Decodable"),
100 cx
.ident_of("decode"));
101 let exprdecode
= cx
.expr_path(cx
.path_global(trait_span
, recurse
));
102 // throw an underscore in front to suppress unused variable warnings
103 let blkarg
= cx
.ident_of("_d");
104 let blkdecoder
= cx
.expr_ident(trait_span
, blkarg
);
106 return match *substr
.fields
{
107 StaticStruct(_
, ref summary
) => {
108 let nfields
= match *summary
{
109 Unnamed(ref fields
) => fields
.len(),
110 Named(ref fields
) => fields
.len()
112 let read_struct_field
= cx
.ident_of("read_struct_field");
114 let path
= cx
.path_ident(trait_span
, substr
.type_ident
);
115 let result
= decode_static_fields(cx
,
119 |cx
, span
, name
, field
| {
121 cx
.expr_method_call(span
, blkdecoder
.clone(), read_struct_field
,
122 vec
!(cx
.expr_str(span
, name
),
123 cx
.expr_usize(span
, field
),
124 exprdecode
.clone())))
126 let result
= cx
.expr_ok(trait_span
, result
);
127 cx
.expr_method_call(trait_span
,
129 cx
.ident_of("read_struct"),
131 cx
.expr_str(trait_span
, token
::get_ident(substr
.type_ident
)),
132 cx
.expr_usize(trait_span
, nfields
),
133 cx
.lambda_expr_1(trait_span
, result
, blkarg
)
136 StaticEnum(_
, ref fields
) => {
137 let variant
= cx
.ident_of("i");
139 let mut arms
= Vec
::new();
140 let mut variants
= Vec
::new();
141 let rvariant_arg
= cx
.ident_of("read_enum_variant_arg");
143 for (i
, &(name
, v_span
, ref parts
)) in fields
.iter().enumerate() {
144 variants
.push(cx
.expr_str(v_span
, token
::get_ident(name
)));
146 let path
= cx
.path(trait_span
, vec
![substr
.type_ident
, name
]);
147 let decoded
= decode_static_fields(cx
,
151 |cx
, span
, _
, field
| {
152 let idx
= cx
.expr_usize(span
, field
);
154 cx
.expr_method_call(span
, blkdecoder
.clone(), rvariant_arg
,
155 vec
!(idx
, exprdecode
.clone())))
158 arms
.push(cx
.arm(v_span
,
159 vec
!(cx
.pat_lit(v_span
, cx
.expr_usize(v_span
, i
))),
163 arms
.push(cx
.arm_unreachable(trait_span
));
165 let result
= cx
.expr_ok(trait_span
,
166 cx
.expr_match(trait_span
,
167 cx
.expr_ident(trait_span
, variant
), arms
));
168 let lambda
= cx
.lambda_expr(trait_span
, vec
!(blkarg
, variant
), result
);
169 let variant_vec
= cx
.expr_vec(trait_span
, variants
);
170 let variant_vec
= cx
.expr_addr_of(trait_span
, variant_vec
);
171 let result
= cx
.expr_method_call(trait_span
, blkdecoder
,
172 cx
.ident_of("read_enum_variant"),
173 vec
!(variant_vec
, lambda
));
174 cx
.expr_method_call(trait_span
,
176 cx
.ident_of("read_enum"),
178 cx
.expr_str(trait_span
, token
::get_ident(substr
.type_ident
)),
179 cx
.lambda_expr_1(trait_span
, result
, blkarg
)
182 _
=> cx
.bug("expected StaticEnum or StaticStruct in derive(Decodable)")
186 /// Create a decoder for a single enum variant/struct:
187 /// - `outer_pat_path` is the path to this enum variant/struct
188 /// - `getarg` should retrieve the `usize`-th field with name `@str`.
189 fn decode_static_fields
<F
>(cx
: &mut ExtCtxt
,
191 outer_pat_path
: ast
::Path
,
192 fields
: &StaticFields
,
195 F
: FnMut(&mut ExtCtxt
, Span
, InternedString
, usize) -> P
<Expr
>,
198 Unnamed(ref fields
) => {
199 let path_expr
= cx
.expr_path(outer_pat_path
);
200 if fields
.is_empty() {
203 let fields
= fields
.iter().enumerate().map(|(i
, &span
)| {
205 token
::intern_and_get_ident(&format
!("_field{}", i
)),
209 cx
.expr_call(trait_span
, path_expr
, fields
)
212 Named(ref fields
) => {
213 // use the field's span to get nicer error messages.
214 let fields
= fields
.iter().enumerate().map(|(i
, &(name
, span
))| {
215 let arg
= getarg(cx
, span
, token
::get_ident(name
), i
);
216 cx
.field_imm(span
, name
, arg
)
218 cx
.expr_struct(trait_span
, outer_pat_path
, fields
)