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