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