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