]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/deriving/rand.rs
597e0959de2df8a4a7ebeeb62580f2c2b7ce6146
[rust.git] / src / libsyntax / ext / deriving / rand.rs
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.
4 //
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.
10
11 use ast;
12 use ast::{MetaItem, Item, Expr, Ident};
13 use codemap::Span;
14 use ext::base::ExtCtxt;
15 use ext::build::{AstBuilder};
16 use ext::deriving::generic::*;
17
18 pub fn expand_deriving_rand(cx: &mut ExtCtxt,
19                             span: Span,
20                             mitem: @MetaItem,
21                             item: @Item,
22                             push: |@Item|) {
23     let trait_def = TraitDef {
24         span: span,
25         attributes: Vec::new(),
26         path: Path::new(vec!("rand", "Rand")),
27         additional_bounds: Vec::new(),
28         generics: LifetimeBounds::empty(),
29         methods: vec!(
30             MethodDef {
31                 name: "rand",
32                 generics: LifetimeBounds {
33                     lifetimes: Vec::new(),
34                     bounds: vec!(("R",
35                                   ast::StaticSize,
36                                   vec!( Path::new(vec!("rand", "Rng")) )))
37                 },
38                 explicit_self: None,
39                 args: vec!(
40                     Ptr(~Literal(Path::new_local("R")),
41                         Borrowed(None, ast::MutMutable))
42                 ),
43                 ret_ty: Self,
44                 attributes: Vec::new(),
45                 const_nonmatching: false,
46                 combine_substructure: rand_substructure
47             }
48         )
49     };
50     trait_def.expand(cx, mitem, item, push)
51 }
52
53 fn rand_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> @Expr {
54     let rng = match substr.nonself_args {
55         [rng] => vec!( rng ),
56         _ => cx.bug("Incorrect number of arguments to `rand` in `deriving(Rand)`")
57     };
58     let rand_ident = vec!(
59         cx.ident_of("rand"),
60         cx.ident_of("Rand"),
61         cx.ident_of("rand")
62     );
63     let rand_call = |cx: &mut ExtCtxt, span| {
64         cx.expr_call_global(span,
65                             rand_ident.clone(),
66                             vec!( *rng.get(0) ))
67     };
68
69     return match *substr.fields {
70         StaticStruct(_, ref summary) => {
71             rand_thing(cx, trait_span, substr.type_ident, summary, rand_call)
72         }
73         StaticEnum(_, ref variants) => {
74             if variants.is_empty() {
75                 cx.span_err(trait_span, "`Rand` cannot be derived for enums with no variants");
76                 // let compilation continue
77                 return cx.expr_uint(trait_span, 0);
78             }
79
80             let variant_count = cx.expr_uint(trait_span, variants.len());
81
82             let rand_name = cx.path_all(trait_span,
83                                         true,
84                                         rand_ident.clone(),
85                                         Vec::new(),
86                                         Vec::new());
87             let rand_name = cx.expr_path(rand_name);
88
89             // ::rand::Rand::rand(rng)
90             let rv_call = cx.expr_call(trait_span,
91                                        rand_name,
92                                        vec!( *rng.get(0) ));
93
94             // need to specify the uint-ness of the random number
95             let uint_ty = cx.ty_ident(trait_span, cx.ident_of("uint"));
96             let value_ident = cx.ident_of("__value");
97             let let_statement = cx.stmt_let_typed(trait_span,
98                                                   false,
99                                                   value_ident,
100                                                   uint_ty,
101                                                   rv_call);
102
103             // rand() % variants.len()
104             let value_ref = cx.expr_ident(trait_span, value_ident);
105             let rand_variant = cx.expr_binary(trait_span,
106                                               ast::BiRem,
107                                               value_ref,
108                                               variant_count);
109
110             let mut arms = variants.iter().enumerate().map(|(i, &(ident, v_span, ref summary))| {
111                 let i_expr = cx.expr_uint(v_span, i);
112                 let pat = cx.pat_lit(v_span, i_expr);
113
114                 let thing = rand_thing(cx, v_span, ident, summary, |cx, sp| rand_call(cx, sp));
115                 cx.arm(v_span, vec!( pat ), thing)
116             }).collect::<Vec<ast::Arm> >();
117
118             // _ => {} at the end. Should never occur
119             arms.push(cx.arm_unreachable(trait_span));
120
121             let match_expr = cx.expr_match(trait_span, rand_variant, arms);
122
123             let block = cx.block(trait_span, vec!( let_statement ), Some(match_expr));
124             cx.expr_block(block)
125         }
126         _ => cx.bug("Non-static method in `deriving(Rand)`")
127     };
128
129     fn rand_thing(cx: &mut ExtCtxt,
130                   trait_span: Span,
131                   ctor_ident: Ident,
132                   summary: &StaticFields,
133                   rand_call: |&mut ExtCtxt, Span| -> @Expr)
134                   -> @Expr {
135         match *summary {
136             Unnamed(ref fields) => {
137                 if fields.is_empty() {
138                     cx.expr_ident(trait_span, ctor_ident)
139                 } else {
140                     let exprs = fields.iter().map(|span| rand_call(cx, *span)).collect();
141                     cx.expr_call_ident(trait_span, ctor_ident, exprs)
142                 }
143             }
144             Named(ref fields) => {
145                 let rand_fields = fields.iter().map(|&(ident, span)| {
146                     let e = rand_call(cx, span);
147                     cx.field_imm(span, ident, e)
148                 }).collect();
149                 cx.expr_struct_ident(trait_span, ctor_ident, rand_fields)
150             }
151         }
152     }
153 }