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