]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/const_eval.rs
rand: Use fill() instead of read()
[rust.git] / src / librustc / middle / const_eval.rs
1 // Copyright 2012-2014 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 #[allow(non_camel_case_types)];
12
13 use metadata::csearch;
14 use middle::astencode;
15
16 use middle::ty;
17 use middle::typeck::astconv;
18 use util::nodemap::{DefIdMap, FnvHashMap, NodeMap};
19
20 use syntax::ast::*;
21 use syntax::parse::token::InternedString;
22 use syntax::visit::Visitor;
23 use syntax::visit;
24 use syntax::{ast, ast_map, ast_util};
25
26 use std::cell::RefCell;
27 use collections::HashMap;
28 use std::rc::Rc;
29
30 //
31 // This pass classifies expressions by their constant-ness.
32 //
33 // Constant-ness comes in 3 flavours:
34 //
35 //   - Integer-constants: can be evaluated by the frontend all the way down
36 //     to their actual value. They are used in a few places (enum
37 //     discriminants, switch arms) and are a subset of
38 //     general-constants. They cover all the integer and integer-ish
39 //     literals (nil, bool, int, uint, char, iNN, uNN) and all integer
40 //     operators and copies applied to them.
41 //
42 //   - General-constants: can be evaluated by LLVM but not necessarily by
43 //     the frontend; usually due to reliance on target-specific stuff such
44 //     as "where in memory the value goes" or "what floating point mode the
45 //     target uses". This _includes_ integer-constants, plus the following
46 //     constructors:
47 //
48 //        fixed-size vectors and strings: [] and ""/_
49 //        vector and string slices: &[] and &""
50 //        tuples: (,)
51 //        records: {...}
52 //        enums: foo(...)
53 //        floating point literals and operators
54 //        & and * pointers
55 //        copies of general constants
56 //
57 //        (in theory, probably not at first: if/match on integer-const
58 //         conditions / descriminants)
59 //
60 //   - Non-constants: everything else.
61 //
62
63 pub enum constness {
64     integral_const,
65     general_const,
66     non_const
67 }
68
69 type constness_cache = DefIdMap<constness>;
70
71 pub fn join(a: constness, b: constness) -> constness {
72     match (a, b) {
73       (integral_const, integral_const) => integral_const,
74       (integral_const, general_const)
75       | (general_const, integral_const)
76       | (general_const, general_const) => general_const,
77       _ => non_const
78     }
79 }
80
81 pub fn join_all<It: Iterator<constness>>(mut cs: It) -> constness {
82     cs.fold(integral_const, |a, b| join(a, b))
83 }
84
85 pub fn lookup_const(tcx: &ty::ctxt, e: &Expr) -> Option<@Expr> {
86     let opt_def = {
87         let def_map = tcx.def_map.borrow();
88         def_map.get().find_copy(&e.id)
89     };
90     match opt_def {
91         Some(ast::DefStatic(def_id, false)) => {
92             lookup_const_by_id(tcx, def_id)
93         }
94         Some(ast::DefVariant(enum_def, variant_def, _)) => {
95             lookup_variant_by_id(tcx, enum_def, variant_def)
96         }
97         _ => None
98     }
99 }
100
101 pub fn lookup_variant_by_id(tcx: &ty::ctxt,
102                             enum_def: ast::DefId,
103                             variant_def: ast::DefId)
104                        -> Option<@Expr> {
105     fn variant_expr(variants: &[ast::P<ast::Variant>], id: ast::NodeId) -> Option<@Expr> {
106         for variant in variants.iter() {
107             if variant.node.id == id {
108                 return variant.node.disr_expr;
109             }
110         }
111         None
112     }
113
114     if ast_util::is_local(enum_def) {
115         {
116             match tcx.map.find(enum_def.node) {
117                 None => None,
118                 Some(ast_map::NodeItem(it)) => match it.node {
119                     ItemEnum(ast::EnumDef { variants: ref variants }, _) => {
120                         variant_expr(variants.as_slice(), variant_def.node)
121                     }
122                     _ => None
123                 },
124                 Some(_) => None
125             }
126         }
127     } else {
128         match tcx.extern_const_variants.borrow().get().find(&variant_def) {
129             Some(&e) => return e,
130             None => {}
131         }
132         let maps = astencode::Maps {
133             root_map: @RefCell::new(HashMap::new()),
134             method_map: @RefCell::new(FnvHashMap::new()),
135             vtable_map: @RefCell::new(NodeMap::new()),
136             capture_map: RefCell::new(NodeMap::new())
137         };
138         let e = match csearch::maybe_get_item_ast(tcx, enum_def,
139             |a, b, c, d| astencode::decode_inlined_item(a, b, &maps, c, d)) {
140             csearch::found(ast::IIItem(item)) => match item.node {
141                 ItemEnum(ast::EnumDef { variants: ref variants }, _) => {
142                     variant_expr(variants.as_slice(), variant_def.node)
143                 }
144                 _ => None
145             },
146             _ => None
147         };
148         tcx.extern_const_variants.borrow_mut().get().insert(variant_def, e);
149         return e;
150     }
151 }
152
153 pub fn lookup_const_by_id(tcx: &ty::ctxt, def_id: ast::DefId)
154                           -> Option<@Expr> {
155     if ast_util::is_local(def_id) {
156         {
157             match tcx.map.find(def_id.node) {
158                 None => None,
159                 Some(ast_map::NodeItem(it)) => match it.node {
160                     ItemStatic(_, ast::MutImmutable, const_expr) => {
161                         Some(const_expr)
162                     }
163                     _ => None
164                 },
165                 Some(_) => None
166             }
167         }
168     } else {
169         {
170             let extern_const_statics = tcx.extern_const_statics.borrow();
171             match extern_const_statics.get().find(&def_id) {
172                 Some(&e) => return e,
173                 None => {}
174             }
175         }
176         let maps = astencode::Maps {
177             root_map: @RefCell::new(HashMap::new()),
178             method_map: @RefCell::new(FnvHashMap::new()),
179             vtable_map: @RefCell::new(NodeMap::new()),
180             capture_map: RefCell::new(NodeMap::new())
181         };
182         let e = match csearch::maybe_get_item_ast(tcx, def_id,
183             |a, b, c, d| astencode::decode_inlined_item(a, b, &maps, c, d)) {
184             csearch::found(ast::IIItem(item)) => match item.node {
185                 ItemStatic(_, ast::MutImmutable, const_expr) => Some(const_expr),
186                 _ => None
187             },
188             _ => None
189         };
190         {
191             let mut extern_const_statics = tcx.extern_const_statics
192                                               .borrow_mut();
193             extern_const_statics.get().insert(def_id, e);
194             return e;
195         }
196     }
197 }
198
199 struct ConstEvalVisitor<'a> {
200     tcx: &'a ty::ctxt,
201     ccache: constness_cache,
202 }
203
204 impl<'a> ConstEvalVisitor<'a> {
205     fn classify(&mut self, e: &Expr) -> constness {
206         let did = ast_util::local_def(e.id);
207         match self.ccache.find(&did) {
208             Some(&x) => return x,
209             None => {}
210         }
211         let cn = match e.node {
212             ast::ExprLit(lit) => {
213                 match lit.node {
214                     ast::LitStr(..) | ast::LitFloat(..) => general_const,
215                     _ => integral_const
216                 }
217             }
218
219             ast::ExprUnary(_, inner) | ast::ExprParen(inner) =>
220                 self.classify(inner),
221
222             ast::ExprBinary(_, a, b) =>
223                 join(self.classify(a), self.classify(b)),
224
225             ast::ExprTup(ref es) |
226             ast::ExprVec(ref es, ast::MutImmutable) =>
227                 join_all(es.iter().map(|e| self.classify(*e))),
228
229             ast::ExprVstore(e, vstore) => {
230                 match vstore {
231                     ast::ExprVstoreSlice => self.classify(e),
232                     ast::ExprVstoreUniq |
233                     ast::ExprVstoreMutSlice => non_const
234                 }
235             }
236
237             ast::ExprStruct(_, ref fs, None) => {
238                 let cs = fs.iter().map(|f| self.classify(f.expr));
239                 join_all(cs)
240             }
241
242             ast::ExprCast(base, _) => {
243                 let ty = ty::expr_ty(self.tcx, e);
244                 let base = self.classify(base);
245                 if ty::type_is_integral(ty) {
246                     join(integral_const, base)
247                 } else if ty::type_is_fp(ty) {
248                     join(general_const, base)
249                 } else {
250                     non_const
251                 }
252             }
253
254             ast::ExprField(base, _, _) => self.classify(base),
255
256             ast::ExprIndex(base, idx) =>
257                 join(self.classify(base), self.classify(idx)),
258
259             ast::ExprAddrOf(ast::MutImmutable, base) => self.classify(base),
260
261             // FIXME: (#3728) we can probably do something CCI-ish
262             // surrounding nonlocal constants. But we don't yet.
263             ast::ExprPath(_) => self.lookup_constness(e),
264
265             ast::ExprRepeat(..) => general_const,
266
267             _ => non_const
268         };
269         self.ccache.insert(did, cn);
270         cn
271     }
272
273     fn lookup_constness(&self, e: &Expr) -> constness {
274         match lookup_const(self.tcx, e) {
275             Some(rhs) => {
276                 let ty = ty::expr_ty(self.tcx, rhs);
277                 if ty::type_is_integral(ty) {
278                     integral_const
279                 } else {
280                     general_const
281                 }
282             }
283             None => non_const
284         }
285     }
286
287 }
288
289 impl<'a> Visitor<()> for ConstEvalVisitor<'a> {
290     fn visit_expr_post(&mut self, e: &Expr, _: ()) {
291         self.classify(e);
292     }
293 }
294
295 pub fn process_crate(krate: &ast::Crate,
296                      tcx: &ty::ctxt) {
297     let mut v = ConstEvalVisitor {
298         tcx: tcx,
299         ccache: DefIdMap::new(),
300     };
301     visit::walk_crate(&mut v, krate, ());
302     tcx.sess.abort_if_errors();
303 }
304
305
306 // FIXME (#33): this doesn't handle big integer/float literals correctly
307 // (nor does the rest of our literal handling).
308 #[deriving(Clone, Eq)]
309 pub enum const_val {
310     const_float(f64),
311     const_int(i64),
312     const_uint(u64),
313     const_str(InternedString),
314     const_binary(Rc<Vec<u8> >),
315     const_bool(bool)
316 }
317
318 pub fn eval_const_expr(tcx: &ty::ctxt, e: &Expr) -> const_val {
319     match eval_const_expr_partial(tcx, e) {
320         Ok(r) => r,
321         Err(s) => tcx.sess.span_fatal(e.span, s)
322     }
323 }
324
325 pub fn eval_const_expr_partial<T: ty::ExprTyProvider>(tcx: &T, e: &Expr)
326                             -> Result<const_val, ~str> {
327     fn fromb(b: bool) -> Result<const_val, ~str> { Ok(const_int(b as i64)) }
328     match e.node {
329       ExprUnary(UnNeg, inner) => {
330         match eval_const_expr_partial(tcx, inner) {
331           Ok(const_float(f)) => Ok(const_float(-f)),
332           Ok(const_int(i)) => Ok(const_int(-i)),
333           Ok(const_uint(i)) => Ok(const_uint(-i)),
334           Ok(const_str(_)) => Err(~"negate on string"),
335           Ok(const_bool(_)) => Err(~"negate on boolean"),
336           ref err => ((*err).clone())
337         }
338       }
339       ExprUnary(UnNot, inner) => {
340         match eval_const_expr_partial(tcx, inner) {
341           Ok(const_int(i)) => Ok(const_int(!i)),
342           Ok(const_uint(i)) => Ok(const_uint(!i)),
343           Ok(const_bool(b)) => Ok(const_bool(!b)),
344           _ => Err(~"not on float or string")
345         }
346       }
347       ExprBinary(op, a, b) => {
348         match (eval_const_expr_partial(tcx, a),
349                eval_const_expr_partial(tcx, b)) {
350           (Ok(const_float(a)), Ok(const_float(b))) => {
351             match op {
352               BiAdd => Ok(const_float(a + b)),
353               BiSub => Ok(const_float(a - b)),
354               BiMul => Ok(const_float(a * b)),
355               BiDiv => Ok(const_float(a / b)),
356               BiRem => Ok(const_float(a % b)),
357               BiEq => fromb(a == b),
358               BiLt => fromb(a < b),
359               BiLe => fromb(a <= b),
360               BiNe => fromb(a != b),
361               BiGe => fromb(a >= b),
362               BiGt => fromb(a > b),
363               _ => Err(~"can't do this op on floats")
364             }
365           }
366           (Ok(const_int(a)), Ok(const_int(b))) => {
367             match op {
368               BiAdd => Ok(const_int(a + b)),
369               BiSub => Ok(const_int(a - b)),
370               BiMul => Ok(const_int(a * b)),
371               BiDiv if b == 0 => Err(~"attempted to divide by zero"),
372               BiDiv => Ok(const_int(a / b)),
373               BiRem if b == 0 => Err(~"attempted remainder with a divisor of zero"),
374               BiRem => Ok(const_int(a % b)),
375               BiAnd | BiBitAnd => Ok(const_int(a & b)),
376               BiOr | BiBitOr => Ok(const_int(a | b)),
377               BiBitXor => Ok(const_int(a ^ b)),
378               BiShl => Ok(const_int(a << b)),
379               BiShr => Ok(const_int(a >> b)),
380               BiEq => fromb(a == b),
381               BiLt => fromb(a < b),
382               BiLe => fromb(a <= b),
383               BiNe => fromb(a != b),
384               BiGe => fromb(a >= b),
385               BiGt => fromb(a > b)
386             }
387           }
388           (Ok(const_uint(a)), Ok(const_uint(b))) => {
389             match op {
390               BiAdd => Ok(const_uint(a + b)),
391               BiSub => Ok(const_uint(a - b)),
392               BiMul => Ok(const_uint(a * b)),
393               BiDiv if b == 0 => Err(~"attempted to divide by zero"),
394               BiDiv => Ok(const_uint(a / b)),
395               BiRem if b == 0 => Err(~"attempted remainder with a divisor of zero"),
396               BiRem => Ok(const_uint(a % b)),
397               BiAnd | BiBitAnd => Ok(const_uint(a & b)),
398               BiOr | BiBitOr => Ok(const_uint(a | b)),
399               BiBitXor => Ok(const_uint(a ^ b)),
400               BiShl => Ok(const_uint(a << b)),
401               BiShr => Ok(const_uint(a >> b)),
402               BiEq => fromb(a == b),
403               BiLt => fromb(a < b),
404               BiLe => fromb(a <= b),
405               BiNe => fromb(a != b),
406               BiGe => fromb(a >= b),
407               BiGt => fromb(a > b),
408             }
409           }
410           // shifts can have any integral type as their rhs
411           (Ok(const_int(a)), Ok(const_uint(b))) => {
412             match op {
413               BiShl => Ok(const_int(a << b)),
414               BiShr => Ok(const_int(a >> b)),
415               _ => Err(~"can't do this op on an int and uint")
416             }
417           }
418           (Ok(const_uint(a)), Ok(const_int(b))) => {
419             match op {
420               BiShl => Ok(const_uint(a << b)),
421               BiShr => Ok(const_uint(a >> b)),
422               _ => Err(~"can't do this op on a uint and int")
423             }
424           }
425           (Ok(const_bool(a)), Ok(const_bool(b))) => {
426             Ok(const_bool(match op {
427               BiAnd => a && b,
428               BiOr => a || b,
429               BiBitXor => a ^ b,
430               BiBitAnd => a & b,
431               BiBitOr => a | b,
432               BiEq => a == b,
433               BiNe => a != b,
434               _ => return Err(~"can't do this op on bools")
435              }))
436           }
437           _ => Err(~"bad operands for binary")
438         }
439       }
440       ExprCast(base, target_ty) => {
441         // This tends to get called w/o the type actually having been
442         // populated in the ctxt, which was causing things to blow up
443         // (#5900). Fall back to doing a limited lookup to get past it.
444         let ety = ty::expr_ty_opt(tcx.ty_ctxt(), e)
445                 .or_else(|| astconv::ast_ty_to_prim_ty(tcx.ty_ctxt(), target_ty))
446                 .unwrap_or_else(|| tcx.ty_ctxt().sess.span_fatal(
447                     target_ty.span,
448                     format!("target type not found for const cast")
449                 ));
450
451         let base = eval_const_expr_partial(tcx, base);
452         match base {
453             Err(_) => base,
454             Ok(val) => {
455                 match ty::get(ety).sty {
456                     ty::ty_float(_) => {
457                         match val {
458                             const_uint(u) => Ok(const_float(u as f64)),
459                             const_int(i) => Ok(const_float(i as f64)),
460                             const_float(f) => Ok(const_float(f)),
461                             _ => Err(~"can't cast float to str"),
462                         }
463                     }
464                     ty::ty_uint(_) => {
465                         match val {
466                             const_uint(u) => Ok(const_uint(u)),
467                             const_int(i) => Ok(const_uint(i as u64)),
468                             const_float(f) => Ok(const_uint(f as u64)),
469                             _ => Err(~"can't cast str to uint"),
470                         }
471                     }
472                     ty::ty_int(_) | ty::ty_bool => {
473                         match val {
474                             const_uint(u) => Ok(const_int(u as i64)),
475                             const_int(i) => Ok(const_int(i)),
476                             const_float(f) => Ok(const_int(f as i64)),
477                             _ => Err(~"can't cast str to int"),
478                         }
479                     }
480                     _ => Err(~"can't cast this type")
481                 }
482             }
483         }
484       }
485       ExprPath(_) => {
486           match lookup_const(tcx.ty_ctxt(), e) {
487               Some(actual_e) => eval_const_expr_partial(tcx.ty_ctxt(), actual_e),
488               None => Err(~"non-constant path in constant expr")
489           }
490       }
491       ExprLit(lit) => Ok(lit_to_const(lit)),
492       // If we have a vstore, just keep going; it has to be a string
493       ExprVstore(e, _) => eval_const_expr_partial(tcx, e),
494       ExprParen(e)     => eval_const_expr_partial(tcx, e),
495       _ => Err(~"unsupported constant expr")
496     }
497 }
498
499 pub fn lit_to_const(lit: &Lit) -> const_val {
500     match lit.node {
501         LitStr(ref s, _) => const_str((*s).clone()),
502         LitBinary(ref data) => {
503             const_binary(Rc::new(data.deref().iter().map(|x| *x).collect()))
504         }
505         LitChar(n) => const_uint(n as u64),
506         LitInt(n, _) => const_int(n),
507         LitUint(n, _) => const_uint(n),
508         LitIntUnsuffixed(n) => const_int(n),
509         LitFloat(ref n, _) | LitFloatUnsuffixed(ref n) => {
510             const_float(from_str::<f64>(n.get()).unwrap() as f64)
511         }
512         LitNil => const_int(0i64),
513         LitBool(b) => const_bool(b)
514     }
515 }
516
517 fn compare_vals<T: Ord>(a: T, b: T) -> Option<int> {
518     Some(if a == b { 0 } else if a < b { -1 } else { 1 })
519 }
520 pub fn compare_const_vals(a: &const_val, b: &const_val) -> Option<int> {
521     match (a, b) {
522         (&const_int(a), &const_int(b)) => compare_vals(a, b),
523         (&const_uint(a), &const_uint(b)) => compare_vals(a, b),
524         (&const_float(a), &const_float(b)) => compare_vals(a, b),
525         (&const_str(ref a), &const_str(ref b)) => compare_vals(a, b),
526         (&const_bool(a), &const_bool(b)) => compare_vals(a, b),
527         _ => None
528     }
529 }
530
531 pub fn compare_lit_exprs(tcx: &ty::ctxt, a: &Expr, b: &Expr) -> Option<int> {
532     compare_const_vals(&eval_const_expr(tcx, a), &eval_const_expr(tcx, b))
533 }
534
535 pub fn lit_expr_eq(tcx: &ty::ctxt, a: &Expr, b: &Expr) -> Option<bool> {
536     compare_lit_exprs(tcx, a, b).map(|val| val == 0)
537 }
538
539 pub fn lit_eq(a: &Lit, b: &Lit) -> Option<bool> {
540     compare_const_vals(&lit_to_const(a), &lit_to_const(b)).map(|val| val == 0)
541 }