1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201

#![feature(box_syntax, plugin_registrar, quote, rustc_private)]

extern crate rustc_plugin;
extern crate syntax;
extern crate syntax_ext;

use rustc_plugin::Registry;
use syntax::ast::{self, Arm, Expr, Field, MetaItem, Mutability};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable, MultiDecorator, ExtCtxt};
use syntax::ext::build::AstBuilder;
use syntax_ext::deriving::generic;
use syntax::parse::token;
use syntax::ptr::P;

#[plugin_registrar]
pub fn plugin_registrar(registry: &mut Registry) {
    registry.register_syntax_extension(token::intern("derive_CerealData"),
        MultiDecorator(box expand)
    );
}

pub fn expand(ecx: &mut ExtCtxt, span: Span, meta_item: &MetaItem, ann: &Annotatable, push: &mut FnMut(Annotatable)) {
    generic::TraitDef {
        span: span,
        attributes: Vec::new(),
        path: generic::ty::Path {
            path: vec!["cereal", "CerealData"],
            lifetime: None,
            params: Vec::new(),
            global: true,
        },
        is_unsafe: true,
        generics: generic::ty::LifetimeBounds::empty(),
        additional_bounds: Vec::new(),
        associated_types: Vec::new(),
        supports_unions: false,
        methods: vec![
            generic::MethodDef {
                name: "read",
                attributes: Vec::new(),
                generics: generic::ty::LifetimeBounds::empty(),
                explicit_self: None,
                ret_ty: generic::ty::Literal(generic::ty::Path {
                    path: vec!["cereal", "CerealResult"],
                    lifetime: None,
                    params: vec![
                        box generic::ty::Self_,
                    ],
                    global: true,
                }),
                is_unsafe: false,
                args: vec![
                    generic::ty::Ptr(box generic::ty::Literal(generic::ty::Path {
                            path: vec!["std", "io", "Read"],
                            lifetime: None,
                            params: Vec::new(),
                            global: true,
                        }),
                        generic::ty::PtrTy::Borrowed(None, Mutability::Mutable)
                    ),
                ],
                unify_fieldless_variants: false,
                combine_substructure: generic::combine_substructure(box read_body),
            },
            generic::MethodDef {
                name: "write",
                attributes: Vec::new(),
                generics: generic::ty::LifetimeBounds::empty(),
                explicit_self: generic::ty::borrowed_explicit_self(),
                ret_ty: generic::ty::Literal(generic::ty::Path {
                    path: vec!["cereal", "CerealResult"],
                    lifetime: None,
                    params: vec![
                        box generic::ty::Tuple(Vec::new()),
                    ],
                    global: true,
                }),
                is_unsafe: false,
                args: vec![
                    generic::ty::Ptr(box generic::ty::Literal(generic::ty::Path {
                            path: vec!["std", "io", "Write"],
                            lifetime: None,
                            params: Vec::new(),
                            global: true,
                        }),
                        generic::ty::PtrTy::Borrowed(None, Mutability::Mutable)
                    ),
                ],
                unify_fieldless_variants: false,
                combine_substructure: generic::combine_substructure(box write_body),
            },
        ],
    }.expand(ecx, meta_item, &ann, push);
}

pub fn read_body(ecx: &mut ExtCtxt, span: Span, substr: &generic::Substructure) -> P<Expr> {
    let ref reader = substr.nonself_args[0];
    let expr = match *substr.fields {
        generic::StaticStruct(_, generic::Unnamed(ref fields, _)) if fields.is_empty() => {
            ecx.expr_ident(span, substr.type_ident)
        },
        generic::StaticStruct(_, generic::Named(ref fields)) if fields.is_empty() => {
            ecx.expr_ident(span, substr.type_ident)
        },
        generic::StaticStruct(_, generic::Unnamed(ref fields, _)) => {
            let all: Vec<P<Expr>> = (0..fields.len()).map(|_| {
                quote_expr!(ecx, try!(::cereal::CerealData::read($reader)))
            }).collect();

            ecx.expr_call_ident(span, substr.type_ident, all)
        },
        generic::StaticStruct(_, generic::Named(ref fields)) => {
            let all: Vec<Field> = fields.iter().map(|&(ident, _)| {
                ecx.field_imm(span, ident, quote_expr!(ecx, try!(::cereal::CerealData::read($reader))))
            }).collect();

            ecx.expr_struct_ident(span, substr.type_ident, all)
        },
        generic::StaticEnum(_, ref variants) => {
            let mut arms: Vec<Arm> = variants.iter().enumerate().map(|(id, &(ident, _, ref fields))| {
                let pat = ecx.pat_lit(span, ecx.expr_lit(span, ast::LitKind::Int(id as u64, ast::LitIntType::Unsigned(ast::UintTy::U64))));
                let ty = substr.type_ident;
                let path = ecx.path(span, vec![ty, ident]);
                let expr = match *fields {
                    generic::Unnamed(ref fields, _) if fields.is_empty() => {
                        ecx.expr_path(path)
                    },
                    generic::Named(ref fields) if fields.is_empty() => {
                        ecx.expr_path(path)
                    },
                    generic::Unnamed(ref fields, _) => {
                        let all: Vec<P<Expr>> = (0..fields.len()).map(|_| {
                            quote_expr!(ecx, try!(::cereal::CerealData::read($reader)))
                        }).collect();

                        ecx.expr_call(span, ecx.expr_path(path), all)
                    },
                    generic::Named(ref fields) => {
                        let all: Vec<Field> = fields.iter().map(|&(ident, _)| {
                            ecx.field_imm(span, ident, quote_expr!(ecx, try!(::cereal::CerealData::read($reader))))
                        }).collect();

                        ecx.expr_struct(span, path, all)
                    },
                };
                ecx.arm(span, vec![pat], expr)
            }).collect();
            arms.push(ecx.arm(span, vec![ecx.pat_wild(span)],
                quote_expr!(ecx,
                    return ::std::result::Result::Err(::cereal::CerealError::Msg("Unknown variant".to_string()))
                )
            ));
            let expr = quote_expr!(ecx, try!(<u64 as ::cereal::CerealData>::read($reader)));
            ecx.expr_match(span, expr, arms)
        },
        _ => {
            ecx.span_err(span, "Deriving CerealData for enums is currently unsupported!");
            return ecx.expr_none(span)
        },
    };
    quote_expr!(ecx, Ok($expr))
}

pub fn write_body(ecx: &mut ExtCtxt, span: Span, substr: &generic::Substructure) -> P<Expr> {
    let ref writer = substr.nonself_args[0];
    match *substr.fields {
        generic::Struct(_, ref fields) => {
            let all: Vec<_> = fields.iter().map(|f| {
                let ref self_ = f.self_;
                quote_stmt!(ecx, {
                    try!(::cereal::CerealData::write(&$self_, $writer));
                }).unwrap()
            }).collect();

            quote_expr!(ecx, {
                $all
                Ok(())
            })
        },
        generic::EnumMatching(var_id, _, ref fields) => {
            let all: Vec<_> = fields.iter().map(|f| {
                let ref self_ = f.self_;
                quote_stmt!(ecx, {
                    try!(::cereal::CerealData::write(&$self_, $writer));
                }).unwrap()
            }).collect();

            quote_expr!(ecx, {
                try!(::cereal::CerealData::write(&($var_id as u64), $writer));
                $all
                Ok(())
            })
        },
        _ => {
            ecx.span_err(span, "Unsupported type for CerealData");
            ecx.expr_none(span)
        }
    }
}