]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/const_eval.rs
0b516a7f05fcf257aac65b8bcd1a1cb34a46aa7a
[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 middle;
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 = HashMap<ast::DefId, 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, variant_def.node)
121                     }
122                     _ => None
123                 },
124                 Some(_) => None
125             }
126         }
127     } else {
128         {
129             let extern_const_variants = tcx.extern_const_variants.borrow();
130             match extern_const_variants.get().find(&variant_def) {
131                 Some(&e) => return e,
132                 None => {}
133             }
134         }
135         let maps = astencode::Maps {
136             root_map: @RefCell::new(HashMap::new()),
137             method_map: @RefCell::new(HashMap::new()),
138             vtable_map: @RefCell::new(HashMap::new()),
139             capture_map: @RefCell::new(HashMap::new())
140         };
141         let e = match csearch::maybe_get_item_ast(tcx, enum_def,
142             |a, b, c, d| astencode::decode_inlined_item(a, b,
143                                                         maps,
144                                                         c, d)) {
145             csearch::found(ast::IIItem(item)) => match item.node {
146                 ItemEnum(ast::EnumDef { variants: ref variants }, _) => {
147                     variant_expr(*variants, variant_def.node)
148                 }
149                 _ => None
150             },
151             _ => None
152         };
153         {
154             let mut extern_const_variants = tcx.extern_const_variants
155                                                .borrow_mut();
156             extern_const_variants.get().insert(variant_def, e);
157             return e;
158         }
159     }
160 }
161
162 pub fn lookup_const_by_id(tcx: ty::ctxt, def_id: ast::DefId)
163                           -> Option<@Expr> {
164     if ast_util::is_local(def_id) {
165         {
166             match tcx.map.find(def_id.node) {
167                 None => None,
168                 Some(ast_map::NodeItem(it)) => match it.node {
169                     ItemStatic(_, ast::MutImmutable, const_expr) => {
170                         Some(const_expr)
171                     }
172                     _ => None
173                 },
174                 Some(_) => None
175             }
176         }
177     } else {
178         {
179             let extern_const_statics = tcx.extern_const_statics.borrow();
180             match extern_const_statics.get().find(&def_id) {
181                 Some(&e) => return e,
182                 None => {}
183             }
184         }
185         let maps = astencode::Maps {
186             root_map: @RefCell::new(HashMap::new()),
187             method_map: @RefCell::new(HashMap::new()),
188             vtable_map: @RefCell::new(HashMap::new()),
189             capture_map: @RefCell::new(HashMap::new())
190         };
191         let e = match csearch::maybe_get_item_ast(tcx, def_id,
192             |a, b, c, d| astencode::decode_inlined_item(a, b, maps, c, d)) {
193             csearch::found(ast::IIItem(item)) => match item.node {
194                 ItemStatic(_, ast::MutImmutable, const_expr) => Some(const_expr),
195                 _ => None
196             },
197             _ => None
198         };
199         {
200             let mut extern_const_statics = tcx.extern_const_statics
201                                               .borrow_mut();
202             extern_const_statics.get().insert(def_id, e);
203             return e;
204         }
205     }
206 }
207
208 struct ConstEvalVisitor {
209     tcx: ty::ctxt,
210     ccache: constness_cache,
211 }
212
213 impl ConstEvalVisitor {
214     fn classify(&mut self, e: &Expr) -> constness {
215         let did = ast_util::local_def(e.id);
216         match self.ccache.find(&did) {
217             Some(&x) => return x,
218             None => {}
219         }
220         let cn = match e.node {
221             ast::ExprLit(lit) => {
222                 match lit.node {
223                     ast::LitStr(..) | ast::LitFloat(..) => general_const,
224                     _ => integral_const
225                 }
226             }
227
228             ast::ExprUnary(_, inner) | ast::ExprParen(inner) =>
229                 self.classify(inner),
230
231             ast::ExprBinary(_, a, b) =>
232                 join(self.classify(a), self.classify(b)),
233
234             ast::ExprTup(ref es) |
235             ast::ExprVec(ref es, ast::MutImmutable) =>
236                 join_all(es.iter().map(|e| self.classify(*e))),
237
238             ast::ExprVstore(e, vstore) => {
239                 match vstore {
240                     ast::ExprVstoreSlice => self.classify(e),
241                     ast::ExprVstoreUniq |
242                     ast::ExprVstoreMutSlice => non_const
243                 }
244             }
245
246             ast::ExprStruct(_, ref fs, None) => {
247                 let cs = fs.iter().map(|f| self.classify(f.expr));
248                 join_all(cs)
249             }
250
251             ast::ExprCast(base, _) => {
252                 let ty = ty::expr_ty(self.tcx, e);
253                 let base = self.classify(base);
254                 if ty::type_is_integral(ty) {
255                     join(integral_const, base)
256                 } else if ty::type_is_fp(ty) {
257                     join(general_const, base)
258                 } else {
259                     non_const
260                 }
261             }
262
263             ast::ExprField(base, _, _) => self.classify(base),
264
265             ast::ExprIndex(base, idx) =>
266                 join(self.classify(base), self.classify(idx)),
267
268             ast::ExprAddrOf(ast::MutImmutable, base) => self.classify(base),
269
270             // FIXME: (#3728) we can probably do something CCI-ish
271             // surrounding nonlocal constants. But we don't yet.
272             ast::ExprPath(_) => self.lookup_constness(e),
273
274             ast::ExprRepeat(..) => general_const,
275
276             _ => non_const
277         };
278         self.ccache.insert(did, cn);
279         cn
280     }
281
282     fn lookup_constness(&self, e: &Expr) -> constness {
283         match lookup_const(self.tcx, e) {
284             Some(rhs) => {
285                 let ty = ty::expr_ty(self.tcx, rhs);
286                 if ty::type_is_integral(ty) {
287                     integral_const
288                 } else {
289                     general_const
290                 }
291             }
292             None => non_const
293         }
294     }
295
296 }
297
298 impl Visitor<()> for ConstEvalVisitor {
299     fn visit_expr_post(&mut self, e: &Expr, _: ()) {
300         self.classify(e);
301     }
302 }
303
304 pub fn process_crate(krate: &ast::Crate,
305                      tcx: ty::ctxt) {
306     let mut v = ConstEvalVisitor {
307         tcx: tcx,
308         ccache: HashMap::new(),
309     };
310     visit::walk_crate(&mut v, krate, ());
311     tcx.sess.abort_if_errors();
312 }
313
314
315 // FIXME (#33): this doesn't handle big integer/float literals correctly
316 // (nor does the rest of our literal handling).
317 #[deriving(Clone, Eq)]
318 pub enum const_val {
319     const_float(f64),
320     const_int(i64),
321     const_uint(u64),
322     const_str(InternedString),
323     const_binary(Rc<~[u8]>),
324     const_bool(bool)
325 }
326
327 pub fn eval_const_expr(tcx: middle::ty::ctxt, e: &Expr) -> const_val {
328     match eval_const_expr_partial(&tcx, e) {
329         Ok(r) => r,
330         Err(s) => tcx.sess.span_fatal(e.span, s)
331     }
332 }
333
334 pub fn eval_const_expr_partial<T: ty::ExprTyProvider>(tcx: &T, e: &Expr)
335                             -> Result<const_val, ~str> {
336     use middle::ty;
337     fn fromb(b: bool) -> Result<const_val, ~str> { Ok(const_int(b as i64)) }
338     match e.node {
339       ExprUnary(UnNeg, inner) => {
340         match eval_const_expr_partial(tcx, inner) {
341           Ok(const_float(f)) => Ok(const_float(-f)),
342           Ok(const_int(i)) => Ok(const_int(-i)),
343           Ok(const_uint(i)) => Ok(const_uint(-i)),
344           Ok(const_str(_)) => Err(~"negate on string"),
345           Ok(const_bool(_)) => Err(~"negate on boolean"),
346           ref err => ((*err).clone())
347         }
348       }
349       ExprUnary(UnNot, inner) => {
350         match eval_const_expr_partial(tcx, inner) {
351           Ok(const_int(i)) => Ok(const_int(!i)),
352           Ok(const_uint(i)) => Ok(const_uint(!i)),
353           Ok(const_bool(b)) => Ok(const_bool(!b)),
354           _ => Err(~"not on float or string")
355         }
356       }
357       ExprBinary(op, a, b) => {
358         match (eval_const_expr_partial(tcx, a),
359                eval_const_expr_partial(tcx, b)) {
360           (Ok(const_float(a)), Ok(const_float(b))) => {
361             match op {
362               BiAdd => Ok(const_float(a + b)),
363               BiSub => Ok(const_float(a - b)),
364               BiMul => Ok(const_float(a * b)),
365               BiDiv => Ok(const_float(a / b)),
366               BiRem => Ok(const_float(a % b)),
367               BiEq => fromb(a == b),
368               BiLt => fromb(a < b),
369               BiLe => fromb(a <= b),
370               BiNe => fromb(a != b),
371               BiGe => fromb(a >= b),
372               BiGt => fromb(a > b),
373               _ => Err(~"can't do this op on floats")
374             }
375           }
376           (Ok(const_int(a)), Ok(const_int(b))) => {
377             match op {
378               BiAdd => Ok(const_int(a + b)),
379               BiSub => Ok(const_int(a - b)),
380               BiMul => Ok(const_int(a * b)),
381               BiDiv if b == 0 => Err(~"attempted to divide by zero"),
382               BiDiv => Ok(const_int(a / b)),
383               BiRem if b == 0 => Err(~"attempted remainder with a divisor of zero"),
384               BiRem => Ok(const_int(a % b)),
385               BiAnd | BiBitAnd => Ok(const_int(a & b)),
386               BiOr | BiBitOr => Ok(const_int(a | b)),
387               BiBitXor => Ok(const_int(a ^ b)),
388               BiShl => Ok(const_int(a << b)),
389               BiShr => Ok(const_int(a >> b)),
390               BiEq => fromb(a == b),
391               BiLt => fromb(a < b),
392               BiLe => fromb(a <= b),
393               BiNe => fromb(a != b),
394               BiGe => fromb(a >= b),
395               BiGt => fromb(a > b)
396             }
397           }
398           (Ok(const_uint(a)), Ok(const_uint(b))) => {
399             match op {
400               BiAdd => Ok(const_uint(a + b)),
401               BiSub => Ok(const_uint(a - b)),
402               BiMul => Ok(const_uint(a * b)),
403               BiDiv if b == 0 => Err(~"attempted to divide by zero"),
404               BiDiv => Ok(const_uint(a / b)),
405               BiRem if b == 0 => Err(~"attempted remainder with a divisor of zero"),
406               BiRem => Ok(const_uint(a % b)),
407               BiAnd | BiBitAnd => Ok(const_uint(a & b)),
408               BiOr | BiBitOr => Ok(const_uint(a | b)),
409               BiBitXor => Ok(const_uint(a ^ b)),
410               BiShl => Ok(const_uint(a << b)),
411               BiShr => Ok(const_uint(a >> b)),
412               BiEq => fromb(a == b),
413               BiLt => fromb(a < b),
414               BiLe => fromb(a <= b),
415               BiNe => fromb(a != b),
416               BiGe => fromb(a >= b),
417               BiGt => fromb(a > b),
418             }
419           }
420           // shifts can have any integral type as their rhs
421           (Ok(const_int(a)), Ok(const_uint(b))) => {
422             match op {
423               BiShl => Ok(const_int(a << b)),
424               BiShr => Ok(const_int(a >> b)),
425               _ => Err(~"can't do this op on an int and uint")
426             }
427           }
428           (Ok(const_uint(a)), Ok(const_int(b))) => {
429             match op {
430               BiShl => Ok(const_uint(a << b)),
431               BiShr => Ok(const_uint(a >> b)),
432               _ => Err(~"can't do this op on a uint and int")
433             }
434           }
435           (Ok(const_bool(a)), Ok(const_bool(b))) => {
436             Ok(const_bool(match op {
437               BiAnd => a && b,
438               BiOr => a || b,
439               BiBitXor => a ^ b,
440               BiBitAnd => a & b,
441               BiBitOr => a | b,
442               BiEq => a == b,
443               BiNe => a != b,
444               _ => return Err(~"can't do this op on bools")
445              }))
446           }
447           _ => Err(~"bad operands for binary")
448         }
449       }
450       ExprCast(base, target_ty) => {
451         // This tends to get called w/o the type actually having been
452         // populated in the ctxt, which was causing things to blow up
453         // (#5900). Fall back to doing a limited lookup to get past it.
454         let ety = ty::expr_ty_opt(tcx.ty_ctxt(), e)
455                 .or_else(|| astconv::ast_ty_to_prim_ty(tcx.ty_ctxt(), target_ty))
456                 .unwrap_or_else(|| tcx.ty_ctxt().sess.span_fatal(
457                     target_ty.span,
458                     format!("target type not found for const cast")
459                 ));
460
461         let base = eval_const_expr_partial(tcx, base);
462         match base {
463             Err(_) => base,
464             Ok(val) => {
465                 match ty::get(ety).sty {
466                     ty::ty_float(_) => {
467                         match val {
468                             const_uint(u) => Ok(const_float(u as f64)),
469                             const_int(i) => Ok(const_float(i as f64)),
470                             const_float(f) => Ok(const_float(f)),
471                             _ => Err(~"can't cast float to str"),
472                         }
473                     }
474                     ty::ty_uint(_) => {
475                         match val {
476                             const_uint(u) => Ok(const_uint(u)),
477                             const_int(i) => Ok(const_uint(i as u64)),
478                             const_float(f) => Ok(const_uint(f as u64)),
479                             _ => Err(~"can't cast str to uint"),
480                         }
481                     }
482                     ty::ty_int(_) | ty::ty_bool => {
483                         match val {
484                             const_uint(u) => Ok(const_int(u as i64)),
485                             const_int(i) => Ok(const_int(i)),
486                             const_float(f) => Ok(const_int(f as i64)),
487                             _ => Err(~"can't cast str to int"),
488                         }
489                     }
490                     _ => Err(~"can't cast this type")
491                 }
492             }
493         }
494       }
495       ExprPath(_) => {
496           match lookup_const(tcx.ty_ctxt(), e) {
497               Some(actual_e) => eval_const_expr_partial(&tcx.ty_ctxt(), actual_e),
498               None => Err(~"non-constant path in constant expr")
499           }
500       }
501       ExprLit(lit) => Ok(lit_to_const(lit)),
502       // If we have a vstore, just keep going; it has to be a string
503       ExprVstore(e, _) => eval_const_expr_partial(tcx, e),
504       ExprParen(e)     => eval_const_expr_partial(tcx, e),
505       _ => Err(~"unsupported constant expr")
506     }
507 }
508
509 pub fn lit_to_const(lit: &Lit) -> const_val {
510     match lit.node {
511         LitStr(ref s, _) => const_str((*s).clone()),
512         LitBinary(ref data) => const_binary(data.clone()),
513         LitChar(n) => const_uint(n as u64),
514         LitInt(n, _) => const_int(n),
515         LitUint(n, _) => const_uint(n),
516         LitIntUnsuffixed(n) => const_int(n),
517         LitFloat(ref n, _) | LitFloatUnsuffixed(ref n) => {
518             const_float(from_str::<f64>(n.get()).unwrap() as f64)
519         }
520         LitNil => const_int(0i64),
521         LitBool(b) => const_bool(b)
522     }
523 }
524
525 fn compare_vals<T : Eq + Ord>(a: T, b: T) -> Option<int> {
526     Some(if a == b { 0 } else if a < b { -1 } else { 1 })
527 }
528 pub fn compare_const_vals(a: &const_val, b: &const_val) -> Option<int> {
529     match (a, b) {
530         (&const_int(a), &const_int(b)) => compare_vals(a, b),
531         (&const_uint(a), &const_uint(b)) => compare_vals(a, b),
532         (&const_float(a), &const_float(b)) => compare_vals(a, b),
533         (&const_str(ref a), &const_str(ref b)) => compare_vals(a, b),
534         (&const_bool(a), &const_bool(b)) => compare_vals(a, b),
535         _ => None
536     }
537 }
538
539 pub fn compare_lit_exprs(tcx: middle::ty::ctxt, a: &Expr, b: &Expr) -> Option<int> {
540     compare_const_vals(&eval_const_expr(tcx, a), &eval_const_expr(tcx, b))
541 }
542
543 pub fn lit_expr_eq(tcx: middle::ty::ctxt, a: &Expr, b: &Expr) -> Option<bool> {
544     compare_lit_exprs(tcx, a, b).map(|val| val == 0)
545 }
546
547 pub fn lit_eq(a: &Lit, b: &Lit) -> Option<bool> {
548     compare_const_vals(&lit_to_const(a), &lit_to_const(b)).map(|val| val == 0)
549 }