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