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