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