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