]> git.lizzy.rs Git - rust.git/blob - src/librustc_const_eval/eval.rs
Rollup merge of #39501 - phungleson:libcorebench, r=alexcrichton
[rust.git] / src / librustc_const_eval / eval.rs
1 // Copyright 2012-2016 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 use rustc::middle::const_val::ConstVal::*;
12 use rustc::middle::const_val::ConstVal;
13 use self::ErrKind::*;
14 use self::EvalHint::*;
15
16 use rustc::hir::map as hir_map;
17 use rustc::hir::map::blocks::FnLikeNode;
18 use rustc::traits;
19 use rustc::hir::def::Def;
20 use rustc::hir::def_id::DefId;
21 use rustc::ty::{self, Ty, TyCtxt};
22 use rustc::ty::util::IntTypeExt;
23 use rustc::ty::subst::Substs;
24 use rustc::traits::Reveal;
25 use rustc::util::common::ErrorReported;
26 use rustc::util::nodemap::DefIdMap;
27
28 use graphviz::IntoCow;
29 use syntax::ast;
30 use rustc::hir::{self, Expr};
31 use syntax::attr::IntType;
32 use syntax_pos::Span;
33
34 use std::borrow::Cow;
35 use std::cmp::Ordering;
36
37 use rustc_const_math::*;
38 use rustc_errors::DiagnosticBuilder;
39
40 macro_rules! math {
41     ($e:expr, $op:expr) => {
42         match $op {
43             Ok(val) => val,
44             Err(e) => signal!($e, Math(e)),
45         }
46     }
47 }
48
49 fn lookup_variant_by_id<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
50                                   variant_def: DefId)
51                                   -> Option<(&'tcx Expr, Option<&'a ty::TypeckTables<'tcx>>)> {
52     if let Some(variant_node_id) = tcx.hir.as_local_node_id(variant_def) {
53         let enum_node_id = tcx.hir.get_parent(variant_node_id);
54         if let Some(hir_map::NodeItem(it)) = tcx.hir.find(enum_node_id) {
55             if let hir::ItemEnum(ref edef, _) = it.node {
56                 for variant in &edef.variants {
57                     if variant.node.data.id() == variant_node_id {
58                         return variant.node.disr_expr.map(|e| {
59                             let def_id = tcx.hir.body_owner_def_id(e);
60                             (&tcx.hir.body(e).value,
61                              tcx.tables.borrow().get(&def_id).cloned())
62                         });
63                     }
64                 }
65             }
66         }
67     }
68     None
69 }
70
71 /// * `def_id` is the id of the constant.
72 /// * `substs` is the monomorphized substitutions for the expression.
73 ///
74 /// `substs` is optional and is used for associated constants.
75 /// This generally happens in late/trans const evaluation.
76 pub fn lookup_const_by_id<'a, 'tcx: 'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
77                                         def_id: DefId,
78                                         substs: Option<&'tcx Substs<'tcx>>)
79                                         -> Option<(&'tcx Expr,
80                                                    Option<&'a ty::TypeckTables<'tcx>>,
81                                                    Option<ty::Ty<'tcx>>)> {
82     if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
83         match tcx.hir.find(node_id) {
84             None => None,
85             Some(hir_map::NodeItem(&hir::Item {
86                 node: hir::ItemConst(ref ty, body), ..
87             })) |
88             Some(hir_map::NodeImplItem(&hir::ImplItem {
89                 node: hir::ImplItemKind::Const(ref ty, body), ..
90             })) => {
91                 Some((&tcx.hir.body(body).value,
92                       tcx.tables.borrow().get(&def_id).cloned(),
93                       tcx.ast_ty_to_prim_ty(ty)))
94             }
95             Some(hir_map::NodeTraitItem(ti)) => match ti.node {
96                 hir::TraitItemKind::Const(ref ty, default) => {
97                     if let Some(substs) = substs {
98                         // If we have a trait item and the substitutions for it,
99                         // `resolve_trait_associated_const` will select an impl
100                         // or the default.
101                         let trait_id = tcx.hir.get_parent(node_id);
102                         let trait_id = tcx.hir.local_def_id(trait_id);
103                         let default_value = default.map(|body| {
104                             (&tcx.hir.body(body).value,
105                              tcx.tables.borrow().get(&def_id).cloned(),
106                              tcx.ast_ty_to_prim_ty(ty))
107                         });
108                         resolve_trait_associated_const(tcx, def_id, default_value, trait_id, substs)
109                     } else {
110                         // Technically, without knowing anything about the
111                         // expression that generates the obligation, we could
112                         // still return the default if there is one. However,
113                         // it's safer to return `None` than to return some value
114                         // that may differ from what you would get from
115                         // correctly selecting an impl.
116                         None
117                     }
118                 }
119                 _ => None
120             },
121             Some(_) => None
122         }
123     } else {
124         let expr_tables_ty = tcx.sess.cstore.maybe_get_item_body(tcx, def_id).map(|body| {
125             (&body.value, Some(tcx.item_tables(def_id)),
126              Some(tcx.sess.cstore.item_type(tcx, def_id)))
127         });
128         match tcx.sess.cstore.describe_def(def_id) {
129             Some(Def::AssociatedConst(_)) => {
130                 let trait_id = tcx.sess.cstore.trait_of_item(def_id);
131                 // As mentioned in the comments above for in-crate
132                 // constants, we only try to find the expression for a
133                 // trait-associated const if the caller gives us the
134                 // substitutions for the reference to it.
135                 if let Some(trait_id) = trait_id {
136                     if let Some(substs) = substs {
137                         resolve_trait_associated_const(tcx, def_id, expr_tables_ty,
138                                                        trait_id, substs)
139                     } else {
140                         None
141                     }
142                 } else {
143                     expr_tables_ty
144                 }
145             },
146             Some(Def::Const(..)) => expr_tables_ty,
147             _ => None
148         }
149     }
150 }
151
152 fn lookup_const_fn_by_id<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
153                                    -> Option<(&'tcx hir::Body, Option<&'a ty::TypeckTables<'tcx>>)>
154 {
155     if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
156         FnLikeNode::from_node(tcx.hir.get(node_id)).and_then(|fn_like| {
157             if fn_like.constness() == hir::Constness::Const {
158                 Some((tcx.hir.body(fn_like.body()),
159                       tcx.tables.borrow().get(&def_id).cloned()))
160             } else {
161                 None
162             }
163         })
164     } else {
165         if tcx.sess.cstore.is_const_fn(def_id) {
166             tcx.sess.cstore.maybe_get_item_body(tcx, def_id).map(|body| {
167                 (body, Some(tcx.item_tables(def_id)))
168             })
169         } else {
170             None
171         }
172     }
173 }
174
175 pub fn report_const_eval_err<'a, 'tcx>(
176     tcx: TyCtxt<'a, 'tcx, 'tcx>,
177     err: &ConstEvalErr,
178     primary_span: Span,
179     primary_kind: &str)
180     -> DiagnosticBuilder<'tcx>
181 {
182     let mut err = err;
183     while let &ConstEvalErr { kind: ErroneousReferencedConstant(box ref i_err), .. } = err {
184         err = i_err;
185     }
186
187     let mut diag = struct_span_err!(tcx.sess, err.span, E0080, "constant evaluation error");
188     note_const_eval_err(tcx, err, primary_span, primary_kind, &mut diag);
189     diag
190 }
191
192 pub fn fatal_const_eval_err<'a, 'tcx>(
193     tcx: TyCtxt<'a, 'tcx, 'tcx>,
194     err: &ConstEvalErr,
195     primary_span: Span,
196     primary_kind: &str)
197     -> !
198 {
199     report_const_eval_err(tcx, err, primary_span, primary_kind).emit();
200     tcx.sess.abort_if_errors();
201     unreachable!()
202 }
203
204 pub fn note_const_eval_err<'a, 'tcx>(
205     _tcx: TyCtxt<'a, 'tcx, 'tcx>,
206     err: &ConstEvalErr,
207     primary_span: Span,
208     primary_kind: &str,
209     diag: &mut DiagnosticBuilder)
210 {
211     match err.description() {
212         ConstEvalErrDescription::Simple(message) => {
213             diag.span_label(err.span, &message);
214         }
215     }
216
217     if !primary_span.contains(err.span) {
218         diag.span_note(primary_span,
219                        &format!("for {} here", primary_kind));
220     }
221 }
222
223 pub struct ConstContext<'a, 'tcx: 'a> {
224     tcx: TyCtxt<'a, 'tcx, 'tcx>,
225     tables: Option<&'a ty::TypeckTables<'tcx>>,
226     fn_args: Option<DefIdMap<ConstVal>>
227 }
228
229 impl<'a, 'tcx> ConstContext<'a, 'tcx> {
230     pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, body: hir::BodyId) -> Self {
231         let def_id = tcx.hir.body_owner_def_id(body);
232         ConstContext {
233             tcx: tcx,
234             tables: tcx.tables.borrow().get(&def_id).cloned(),
235             fn_args: None
236         }
237     }
238
239     pub fn with_tables(tcx: TyCtxt<'a, 'tcx, 'tcx>, tables: &'a ty::TypeckTables<'tcx>) -> Self {
240         ConstContext {
241             tcx: tcx,
242             tables: Some(tables),
243             fn_args: None
244         }
245     }
246
247     /// Evaluate a constant expression in a context where the expression isn't
248     /// guaranteed to be evaluatable. `ty_hint` is usually ExprTypeChecked,
249     /// but a few places need to evaluate constants during type-checking, like
250     /// computing the length of an array. (See also the FIXME above EvalHint.)
251     pub fn eval(&self, e: &Expr, ty_hint: EvalHint<'tcx>) -> EvalResult {
252         eval_const_expr_partial(self, e, ty_hint)
253     }
254 }
255
256 #[derive(Clone, Debug)]
257 pub struct ConstEvalErr {
258     pub span: Span,
259     pub kind: ErrKind,
260 }
261
262 #[derive(Clone, Debug)]
263 pub enum ErrKind {
264     CannotCast,
265     CannotCastTo(&'static str),
266     InvalidOpForInts(hir::BinOp_),
267     InvalidOpForBools(hir::BinOp_),
268     InvalidOpForFloats(hir::BinOp_),
269     InvalidOpForIntUint(hir::BinOp_),
270     InvalidOpForUintInt(hir::BinOp_),
271     NegateOn(ConstVal),
272     NotOn(ConstVal),
273     CallOn(ConstVal),
274
275     MissingStructField,
276     NonConstPath,
277     UnimplementedConstVal(&'static str),
278     UnresolvedPath,
279     ExpectedConstTuple,
280     ExpectedConstStruct,
281     TupleIndexOutOfBounds,
282     IndexedNonVec,
283     IndexNegative,
284     IndexNotInt,
285     IndexOutOfBounds { len: u64, index: u64 },
286     RepeatCountNotNatural,
287     RepeatCountNotInt,
288
289     MiscBinaryOp,
290     MiscCatchAll,
291
292     IndexOpFeatureGated,
293     Math(ConstMathErr),
294
295     IntermediateUnsignedNegative,
296     /// Expected, Got
297     TypeMismatch(String, ConstInt),
298
299     BadType(ConstVal),
300     ErroneousReferencedConstant(Box<ConstEvalErr>),
301     CharCast(ConstInt),
302 }
303
304 impl From<ConstMathErr> for ErrKind {
305     fn from(err: ConstMathErr) -> ErrKind {
306         Math(err)
307     }
308 }
309
310 #[derive(Clone, Debug)]
311 pub enum ConstEvalErrDescription<'a> {
312     Simple(Cow<'a, str>),
313 }
314
315 impl<'a> ConstEvalErrDescription<'a> {
316     /// Return a one-line description of the error, for lints and such
317     pub fn into_oneline(self) -> Cow<'a, str> {
318         match self {
319             ConstEvalErrDescription::Simple(simple) => simple,
320         }
321     }
322 }
323
324 impl ConstEvalErr {
325     pub fn description(&self) -> ConstEvalErrDescription {
326         use self::ErrKind::*;
327         use self::ConstEvalErrDescription::*;
328
329         macro_rules! simple {
330             ($msg:expr) => ({ Simple($msg.into_cow()) });
331             ($fmt:expr, $($arg:tt)+) => ({
332                 Simple(format!($fmt, $($arg)+).into_cow())
333             })
334         }
335
336         match self.kind {
337             CannotCast => simple!("can't cast this type"),
338             CannotCastTo(s) => simple!("can't cast this type to {}", s),
339             InvalidOpForInts(_) =>  simple!("can't do this op on integrals"),
340             InvalidOpForBools(_) =>  simple!("can't do this op on bools"),
341             InvalidOpForFloats(_) => simple!("can't do this op on floats"),
342             InvalidOpForIntUint(..) => simple!("can't do this op on an isize and usize"),
343             InvalidOpForUintInt(..) => simple!("can't do this op on a usize and isize"),
344             NegateOn(ref const_val) => simple!("negate on {}", const_val.description()),
345             NotOn(ref const_val) => simple!("not on {}", const_val.description()),
346             CallOn(ref const_val) => simple!("call on {}", const_val.description()),
347
348             MissingStructField  => simple!("nonexistent struct field"),
349             NonConstPath        => simple!("non-constant path in constant expression"),
350             UnimplementedConstVal(what) =>
351                 simple!("unimplemented constant expression: {}", what),
352             UnresolvedPath => simple!("unresolved path in constant expression"),
353             ExpectedConstTuple => simple!("expected constant tuple"),
354             ExpectedConstStruct => simple!("expected constant struct"),
355             TupleIndexOutOfBounds => simple!("tuple index out of bounds"),
356             IndexedNonVec => simple!("indexing is only supported for arrays"),
357             IndexNegative => simple!("indices must be non-negative integers"),
358             IndexNotInt => simple!("indices must be integers"),
359             IndexOutOfBounds { len, index } => {
360                 simple!("index out of bounds: the len is {} but the index is {}",
361                         len, index)
362             }
363             RepeatCountNotNatural => simple!("repeat count must be a natural number"),
364             RepeatCountNotInt => simple!("repeat count must be integers"),
365
366             MiscBinaryOp => simple!("bad operands for binary"),
367             MiscCatchAll => simple!("unsupported constant expr"),
368             IndexOpFeatureGated => simple!("the index operation on const values is unstable"),
369             Math(ref err) => Simple(err.description().into_cow()),
370
371             IntermediateUnsignedNegative => simple!(
372                 "during the computation of an unsigned a negative \
373                  number was encountered. This is most likely a bug in\
374                  the constant evaluator"),
375
376             TypeMismatch(ref expected, ref got) => {
377                 simple!("expected {}, found {}", expected, got.description())
378             },
379             BadType(ref i) => simple!("value of wrong type: {:?}", i),
380             ErroneousReferencedConstant(_) => simple!("could not evaluate referenced constant"),
381             CharCast(ref got) => {
382                 simple!("only `u8` can be cast as `char`, not `{}`", got.description())
383             },
384         }
385     }
386 }
387
388 pub type EvalResult = Result<ConstVal, ConstEvalErr>;
389 pub type CastResult = Result<ConstVal, ErrKind>;
390
391 // FIXME: Long-term, this enum should go away: trying to evaluate
392 // an expression which hasn't been type-checked is a recipe for
393 // disaster.  That said, it's not clear how to fix ast_ty_to_ty
394 // to avoid the ordering issue.
395
396 /// Hint to determine how to evaluate constant expressions which
397 /// might not be type-checked.
398 #[derive(Copy, Clone, Debug)]
399 pub enum EvalHint<'tcx> {
400     /// We have a type-checked expression.
401     ExprTypeChecked,
402     /// We have an expression which hasn't been type-checked, but we have
403     /// an idea of what the type will be because of the context. For example,
404     /// the length of an array is always `usize`. (This is referred to as
405     /// a hint because it isn't guaranteed to be consistent with what
406     /// type-checking would compute.)
407     UncheckedExprHint(Ty<'tcx>),
408     /// We have an expression which has not yet been type-checked, and
409     /// and we have no clue what the type will be.
410     UncheckedExprNoHint,
411 }
412
413 impl<'tcx> EvalHint<'tcx> {
414     fn erase_hint(&self) -> EvalHint<'tcx> {
415         match *self {
416             ExprTypeChecked => ExprTypeChecked,
417             UncheckedExprHint(_) | UncheckedExprNoHint => UncheckedExprNoHint,
418         }
419     }
420     fn checked_or(&self, ty: Ty<'tcx>) -> EvalHint<'tcx> {
421         match *self {
422             ExprTypeChecked => ExprTypeChecked,
423             _ => UncheckedExprHint(ty),
424         }
425     }
426 }
427
428 macro_rules! signal {
429     ($e:expr, $exn:expr) => {
430         return Err(ConstEvalErr { span: $e.span, kind: $exn })
431     }
432 }
433
434 fn eval_const_expr_partial<'a, 'tcx>(cx: &ConstContext<'a, 'tcx>,
435                                      e: &Expr,
436                                      ty_hint: EvalHint<'tcx>) -> EvalResult {
437     let tcx = cx.tcx;
438     // Try to compute the type of the expression based on the EvalHint.
439     // (See also the definition of EvalHint, and the FIXME above EvalHint.)
440     let ety = match ty_hint {
441         ExprTypeChecked => {
442             // After type-checking, expr_ty is guaranteed to succeed.
443             cx.tables.map(|tables| tables.expr_ty(e))
444         }
445         UncheckedExprHint(ty) => {
446             // Use the type hint; it's not guaranteed to be right, but it's
447             // usually good enough.
448             Some(ty)
449         }
450         UncheckedExprNoHint => {
451             // This expression might not be type-checked, and we have no hint.
452             // Try to query the context for a type anyway; we might get lucky
453             // (for example, if the expression was imported from another crate).
454             cx.tables.and_then(|tables| tables.expr_ty_opt(e))
455         }
456     };
457     let result = match e.node {
458       hir::ExprUnary(hir::UnNeg, ref inner) => {
459         // unary neg literals already got their sign during creation
460         if let hir::ExprLit(ref lit) = inner.node {
461             use syntax::ast::*;
462             use syntax::ast::LitIntType::*;
463             const I8_OVERFLOW: u128 = i8::min_value() as u8 as u128;
464             const I16_OVERFLOW: u128 = i16::min_value() as u16 as u128;
465             const I32_OVERFLOW: u128 = i32::min_value() as u32 as u128;
466             const I64_OVERFLOW: u128 = i64::min_value() as u64 as u128;
467             const I128_OVERFLOW: u128 = i128::min_value() as u128;
468             match (&lit.node, ety.map(|t| &t.sty)) {
469                 (&LitKind::Int(I8_OVERFLOW, _), Some(&ty::TyInt(IntTy::I8))) |
470                 (&LitKind::Int(I8_OVERFLOW, Signed(IntTy::I8)), _) => {
471                     return Ok(Integral(I8(i8::min_value())))
472                 },
473                 (&LitKind::Int(I16_OVERFLOW, _), Some(&ty::TyInt(IntTy::I16))) |
474                 (&LitKind::Int(I16_OVERFLOW, Signed(IntTy::I16)), _) => {
475                     return Ok(Integral(I16(i16::min_value())))
476                 },
477                 (&LitKind::Int(I32_OVERFLOW, _), Some(&ty::TyInt(IntTy::I32))) |
478                 (&LitKind::Int(I32_OVERFLOW, Signed(IntTy::I32)), _) => {
479                     return Ok(Integral(I32(i32::min_value())))
480                 },
481                 (&LitKind::Int(I64_OVERFLOW, _), Some(&ty::TyInt(IntTy::I64))) |
482                 (&LitKind::Int(I64_OVERFLOW, Signed(IntTy::I64)), _) => {
483                     return Ok(Integral(I64(i64::min_value())))
484                 },
485                 (&LitKind::Int(n, _), Some(&ty::TyInt(IntTy::I128))) |
486                 (&LitKind::Int(n, Signed(IntTy::I128)), _) => {
487                     // SNAP: replace n in pattern with I128_OVERFLOW and remove this if.
488                     if n == I128_OVERFLOW {
489                         return Ok(Integral(I128(i128::min_value())))
490                     }
491                 },
492                 (&LitKind::Int(n, _), Some(&ty::TyInt(IntTy::Is))) |
493                 (&LitKind::Int(n, Signed(IntTy::Is)), _) => {
494                     match tcx.sess.target.int_type {
495                         IntTy::I16 => if n == I16_OVERFLOW {
496                             return Ok(Integral(Isize(Is16(i16::min_value()))));
497                         },
498                         IntTy::I32 => if n == I32_OVERFLOW {
499                             return Ok(Integral(Isize(Is32(i32::min_value()))));
500                         },
501                         IntTy::I64 => if n == I64_OVERFLOW {
502                             return Ok(Integral(Isize(Is64(i64::min_value()))));
503                         },
504                         _ => bug!(),
505                     }
506                 },
507                 _ => {},
508             }
509         }
510         match cx.eval(inner, ty_hint)? {
511           Float(f) => Float(-f),
512           Integral(i) => Integral(math!(e, -i)),
513           const_val => signal!(e, NegateOn(const_val)),
514         }
515       }
516       hir::ExprUnary(hir::UnNot, ref inner) => {
517         match cx.eval(inner, ty_hint)? {
518           Integral(i) => Integral(math!(e, !i)),
519           Bool(b) => Bool(!b),
520           const_val => signal!(e, NotOn(const_val)),
521         }
522       }
523       hir::ExprUnary(hir::UnDeref, _) => signal!(e, UnimplementedConstVal("deref operation")),
524       hir::ExprBinary(op, ref a, ref b) => {
525         let b_ty = match op.node {
526             hir::BiShl | hir::BiShr => ty_hint.erase_hint(),
527             _ => ty_hint
528         };
529         // technically, if we don't have type hints, but integral eval
530         // gives us a type through a type-suffix, cast or const def type
531         // we need to re-eval the other value of the BinOp if it was
532         // not inferred
533         match (cx.eval(a, ty_hint)?,
534                cx.eval(b, b_ty)?) {
535           (Float(a), Float(b)) => {
536             use std::cmp::Ordering::*;
537             match op.node {
538               hir::BiAdd => Float(math!(e, a + b)),
539               hir::BiSub => Float(math!(e, a - b)),
540               hir::BiMul => Float(math!(e, a * b)),
541               hir::BiDiv => Float(math!(e, a / b)),
542               hir::BiRem => Float(math!(e, a % b)),
543               hir::BiEq => Bool(math!(e, a.try_cmp(b)) == Equal),
544               hir::BiLt => Bool(math!(e, a.try_cmp(b)) == Less),
545               hir::BiLe => Bool(math!(e, a.try_cmp(b)) != Greater),
546               hir::BiNe => Bool(math!(e, a.try_cmp(b)) != Equal),
547               hir::BiGe => Bool(math!(e, a.try_cmp(b)) != Less),
548               hir::BiGt => Bool(math!(e, a.try_cmp(b)) == Greater),
549               _ => signal!(e, InvalidOpForFloats(op.node)),
550             }
551           }
552           (Integral(a), Integral(b)) => {
553             use std::cmp::Ordering::*;
554             match op.node {
555               hir::BiAdd => Integral(math!(e, a + b)),
556               hir::BiSub => Integral(math!(e, a - b)),
557               hir::BiMul => Integral(math!(e, a * b)),
558               hir::BiDiv => Integral(math!(e, a / b)),
559               hir::BiRem => Integral(math!(e, a % b)),
560               hir::BiBitAnd => Integral(math!(e, a & b)),
561               hir::BiBitOr => Integral(math!(e, a | b)),
562               hir::BiBitXor => Integral(math!(e, a ^ b)),
563               hir::BiShl => Integral(math!(e, a << b)),
564               hir::BiShr => Integral(math!(e, a >> b)),
565               hir::BiEq => Bool(math!(e, a.try_cmp(b)) == Equal),
566               hir::BiLt => Bool(math!(e, a.try_cmp(b)) == Less),
567               hir::BiLe => Bool(math!(e, a.try_cmp(b)) != Greater),
568               hir::BiNe => Bool(math!(e, a.try_cmp(b)) != Equal),
569               hir::BiGe => Bool(math!(e, a.try_cmp(b)) != Less),
570               hir::BiGt => Bool(math!(e, a.try_cmp(b)) == Greater),
571               _ => signal!(e, InvalidOpForInts(op.node)),
572             }
573           }
574           (Bool(a), Bool(b)) => {
575             Bool(match op.node {
576               hir::BiAnd => a && b,
577               hir::BiOr => a || b,
578               hir::BiBitXor => a ^ b,
579               hir::BiBitAnd => a & b,
580               hir::BiBitOr => a | b,
581               hir::BiEq => a == b,
582               hir::BiNe => a != b,
583               hir::BiLt => a < b,
584               hir::BiLe => a <= b,
585               hir::BiGe => a >= b,
586               hir::BiGt => a > b,
587               _ => signal!(e, InvalidOpForBools(op.node)),
588              })
589           }
590
591           _ => signal!(e, MiscBinaryOp),
592         }
593       }
594       hir::ExprCast(ref base, ref target_ty) => {
595         let ety = tcx.ast_ty_to_prim_ty(&target_ty).or(ety)
596                 .unwrap_or_else(|| {
597                     tcx.sess.span_fatal(target_ty.span,
598                                         "target type not found for const cast")
599                 });
600
601         let base_hint = if let ExprTypeChecked = ty_hint {
602             ExprTypeChecked
603         } else {
604             match cx.tables.and_then(|tables| tables.expr_ty_opt(&base)) {
605                 Some(t) => UncheckedExprHint(t),
606                 None => ty_hint
607             }
608         };
609
610         let val = match cx.eval(base, base_hint) {
611             Ok(val) => val,
612             Err(ConstEvalErr { kind: ErroneousReferencedConstant(
613                 box ConstEvalErr { kind: TypeMismatch(_, val), .. }), .. }) |
614             Err(ConstEvalErr { kind: TypeMismatch(_, val), .. }) => {
615                 // Something like `5i8 as usize` doesn't need a type hint for the base
616                 // instead take the type hint from the inner value
617                 let hint = match val.int_type() {
618                     Some(IntType::UnsignedInt(ty)) => ty_hint.checked_or(tcx.mk_mach_uint(ty)),
619                     Some(IntType::SignedInt(ty)) => ty_hint.checked_or(tcx.mk_mach_int(ty)),
620                     // we had a type hint, so we can't have an unknown type
621                     None => bug!(),
622                 };
623                 cx.eval(base, hint)?
624             },
625             Err(e) => return Err(e),
626         };
627         match cast_const(tcx, val, ety) {
628             Ok(val) => val,
629             Err(kind) => return Err(ConstEvalErr { span: e.span, kind: kind }),
630         }
631       }
632       hir::ExprPath(ref qpath) => {
633           let def = cx.tables.map(|tables| tables.qpath_def(qpath, e.id)).unwrap_or_else(|| {
634             // There are no tables so we can only handle already-resolved HIR.
635             match *qpath {
636                 hir::QPath::Resolved(_, ref path) => path.def,
637                 hir::QPath::TypeRelative(..) => Def::Err
638             }
639           });
640           match def {
641               Def::Const(def_id) |
642               Def::AssociatedConst(def_id) => {
643                   let substs = if let ExprTypeChecked = ty_hint {
644                       Some(cx.tables.and_then(|tables| tables.node_id_item_substs(e.id))
645                         .unwrap_or_else(|| tcx.intern_substs(&[])))
646                   } else {
647                       None
648                   };
649                   if let Some((expr, tables, ty)) = lookup_const_by_id(tcx, def_id, substs) {
650                       let item_hint = match ty {
651                           Some(ty) => ty_hint.checked_or(ty),
652                           None => ty_hint,
653                       };
654                       let cx = ConstContext { tcx: tcx, tables: tables, fn_args: None };
655                       match cx.eval(expr, item_hint) {
656                           Ok(val) => val,
657                           Err(err) => {
658                               debug!("bad reference: {:?}, {:?}", err.description(), err.span);
659                               signal!(e, ErroneousReferencedConstant(box err))
660                           },
661                       }
662                   } else {
663                       signal!(e, NonConstPath);
664                   }
665               },
666               Def::VariantCtor(variant_def, ..) => {
667                   if let Some((expr, tables)) = lookup_variant_by_id(tcx, variant_def) {
668                       let cx = ConstContext { tcx: tcx, tables: tables, fn_args: None };
669                       match cx.eval(expr, ty_hint) {
670                           Ok(val) => val,
671                           Err(err) => {
672                               debug!("bad reference: {:?}, {:?}", err.description(), err.span);
673                               signal!(e, ErroneousReferencedConstant(box err))
674                           },
675                       }
676                   } else {
677                       signal!(e, UnimplementedConstVal("enum variants"));
678                   }
679               }
680               Def::StructCtor(..) => {
681                   ConstVal::Struct(Default::default())
682               }
683               Def::Local(def_id) => {
684                   debug!("Def::Local({:?}): {:?}", def_id, cx.fn_args);
685                   if let Some(val) = cx.fn_args.as_ref().and_then(|args| args.get(&def_id)) {
686                       val.clone()
687                   } else {
688                       signal!(e, NonConstPath);
689                   }
690               },
691               Def::Method(id) | Def::Fn(id) => Function(id),
692               Def::Err => signal!(e, UnresolvedPath),
693               _ => signal!(e, NonConstPath),
694           }
695       }
696       hir::ExprCall(ref callee, ref args) => {
697           let sub_ty_hint = ty_hint.erase_hint();
698           let callee_val = cx.eval(callee, sub_ty_hint)?;
699           let did = match callee_val {
700               Function(did) => did,
701               Struct(_) => signal!(e, UnimplementedConstVal("tuple struct constructors")),
702               callee => signal!(e, CallOn(callee)),
703           };
704           let (body, tables) = match lookup_const_fn_by_id(tcx, did) {
705               Some(x) => x,
706               None => signal!(e, NonConstPath),
707           };
708
709           let arg_defs = body.arguments.iter().map(|arg| match arg.pat.node {
710                hir::PatKind::Binding(_, def_id, _, _) => Some(def_id),
711                _ => None
712            }).collect::<Vec<_>>();
713           assert_eq!(arg_defs.len(), args.len());
714
715           let mut call_args = DefIdMap();
716           for (arg, arg_expr) in arg_defs.into_iter().zip(args.iter()) {
717               let arg_hint = ty_hint.erase_hint();
718               let arg_val = cx.eval(arg_expr, arg_hint)?;
719               debug!("const call arg: {:?}", arg);
720               if let Some(def_id) = arg {
721                 assert!(call_args.insert(def_id, arg_val).is_none());
722               }
723           }
724           debug!("const call({:?})", call_args);
725           let callee_cx = ConstContext {
726             tcx: tcx,
727             tables: tables,
728             fn_args: Some(call_args)
729           };
730           callee_cx.eval(&body.value, ty_hint)?
731       },
732       hir::ExprLit(ref lit) => match lit_to_const(&lit.node, tcx, ety) {
733           Ok(val) => val,
734           Err(err) => signal!(e, err),
735       },
736       hir::ExprBlock(ref block) => {
737         match block.expr {
738             Some(ref expr) => cx.eval(expr, ty_hint)?,
739             None => signal!(e, UnimplementedConstVal("empty block")),
740         }
741       }
742       hir::ExprType(ref e, _) => cx.eval(e, ty_hint)?,
743       hir::ExprTup(ref fields) => {
744         let field_hint = ty_hint.erase_hint();
745         Tuple(fields.iter().map(|e| cx.eval(e, field_hint)).collect::<Result<_, _>>()?)
746       }
747       hir::ExprStruct(_, ref fields, _) => {
748         let field_hint = ty_hint.erase_hint();
749         Struct(fields.iter().map(|f| {
750             cx.eval(&f.expr, field_hint).map(|v| (f.name.node, v))
751         }).collect::<Result<_, _>>()?)
752       }
753       hir::ExprIndex(ref arr, ref idx) => {
754         if !tcx.sess.features.borrow().const_indexing {
755             signal!(e, IndexOpFeatureGated);
756         }
757         let arr_hint = ty_hint.erase_hint();
758         let arr = cx.eval(arr, arr_hint)?;
759         let idx_hint = ty_hint.checked_or(tcx.types.usize);
760         let idx = match cx.eval(idx, idx_hint)? {
761             Integral(Usize(i)) => i.as_u64(tcx.sess.target.uint_type),
762             Integral(_) => bug!(),
763             _ => signal!(idx, IndexNotInt),
764         };
765         assert_eq!(idx as usize as u64, idx);
766         match arr {
767             Array(ref v) => {
768                 if let Some(elem) = v.get(idx as usize) {
769                     elem.clone()
770                 } else {
771                     let n = v.len() as u64;
772                     assert_eq!(n as usize as u64, n);
773                     signal!(e, IndexOutOfBounds { len: n, index: idx })
774                 }
775             }
776
777             Repeat(.., n) if idx >= n => {
778                 signal!(e, IndexOutOfBounds { len: n, index: idx })
779             }
780             Repeat(ref elem, _) => (**elem).clone(),
781
782             ByteStr(ref data) if idx >= data.len() as u64 => {
783                 signal!(e, IndexOutOfBounds { len: data.len() as u64, index: idx })
784             }
785             ByteStr(data) => {
786                 Integral(U8(data[idx as usize]))
787             },
788
789             _ => signal!(e, IndexedNonVec),
790         }
791       }
792       hir::ExprArray(ref v) => {
793         let elem_hint = ty_hint.erase_hint();
794         Array(v.iter().map(|e| cx.eval(e, elem_hint)).collect::<Result<_, _>>()?)
795       }
796       hir::ExprRepeat(ref elem, count) => {
797           let elem_hint = ty_hint.erase_hint();
798           let len_hint = ty_hint.checked_or(tcx.types.usize);
799           let n = if let Some(ty) = ety {
800             // For cross-crate constants, we have the type already,
801             // but not the body for `count`, so use the type.
802             match ty.sty {
803                 ty::TyArray(_, n) => n as u64,
804                 _ => bug!()
805             }
806           } else {
807             let n = &tcx.hir.body(count).value;
808             match ConstContext::new(tcx, count).eval(n, len_hint)? {
809                 Integral(Usize(i)) => i.as_u64(tcx.sess.target.uint_type),
810                 Integral(_) => signal!(e, RepeatCountNotNatural),
811                 _ => signal!(e, RepeatCountNotInt),
812             }
813           };
814           Repeat(Box::new(cx.eval(elem, elem_hint)?), n)
815       },
816       hir::ExprTupField(ref base, index) => {
817         let base_hint = ty_hint.erase_hint();
818         let c = cx.eval(base, base_hint)?;
819         if let Tuple(ref fields) = c {
820             if let Some(elem) = fields.get(index.node) {
821                 elem.clone()
822             } else {
823                 signal!(e, TupleIndexOutOfBounds);
824             }
825         } else {
826             signal!(base, ExpectedConstTuple);
827         }
828       }
829       hir::ExprField(ref base, field_name) => {
830         let base_hint = ty_hint.erase_hint();
831         let c = cx.eval(base, base_hint)?;
832         if let Struct(ref fields) = c {
833             if let Some(f) = fields.get(&field_name.node) {
834                 f.clone()
835             } else {
836                 signal!(e, MissingStructField);
837             }
838         } else {
839             signal!(base, ExpectedConstStruct);
840         }
841       }
842       hir::ExprAddrOf(..) => signal!(e, UnimplementedConstVal("address operator")),
843       _ => signal!(e, MiscCatchAll)
844     };
845
846     match (ety.map(|t| &t.sty), result) {
847         (Some(ref ty_hint), Integral(i)) => match infer(i, tcx, ty_hint) {
848             Ok(inferred) => Ok(Integral(inferred)),
849             Err(err) => signal!(e, err),
850         },
851         (_, result) => Ok(result),
852     }
853 }
854
855 fn infer<'a, 'tcx>(i: ConstInt,
856                    tcx: TyCtxt<'a, 'tcx, 'tcx>,
857                    ty_hint: &ty::TypeVariants<'tcx>)
858                    -> Result<ConstInt, ErrKind> {
859     use syntax::ast::*;
860
861     match (ty_hint, i) {
862         (&ty::TyInt(IntTy::I8), result @ I8(_)) => Ok(result),
863         (&ty::TyInt(IntTy::I16), result @ I16(_)) => Ok(result),
864         (&ty::TyInt(IntTy::I32), result @ I32(_)) => Ok(result),
865         (&ty::TyInt(IntTy::I64), result @ I64(_)) => Ok(result),
866         (&ty::TyInt(IntTy::I128), result @ I128(_)) => Ok(result),
867         (&ty::TyInt(IntTy::Is), result @ Isize(_)) => Ok(result),
868
869         (&ty::TyUint(UintTy::U8), result @ U8(_)) => Ok(result),
870         (&ty::TyUint(UintTy::U16), result @ U16(_)) => Ok(result),
871         (&ty::TyUint(UintTy::U32), result @ U32(_)) => Ok(result),
872         (&ty::TyUint(UintTy::U64), result @ U64(_)) => Ok(result),
873         (&ty::TyUint(UintTy::U128), result @ U128(_)) => Ok(result),
874         (&ty::TyUint(UintTy::Us), result @ Usize(_)) => Ok(result),
875
876         (&ty::TyInt(IntTy::I8), Infer(i)) => Ok(I8(i as i128 as i8)),
877         (&ty::TyInt(IntTy::I16), Infer(i)) => Ok(I16(i as i128 as i16)),
878         (&ty::TyInt(IntTy::I32), Infer(i)) => Ok(I32(i as i128 as i32)),
879         (&ty::TyInt(IntTy::I64), Infer(i)) => Ok(I64(i as i128 as i64)),
880         (&ty::TyInt(IntTy::I128), Infer(i)) => Ok(I128(i as i128)),
881         (&ty::TyInt(IntTy::Is), Infer(i)) => {
882             Ok(Isize(ConstIsize::new_truncating(i as i128, tcx.sess.target.int_type)))
883         },
884
885         (&ty::TyInt(IntTy::I8), InferSigned(i)) => Ok(I8(i as i8)),
886         (&ty::TyInt(IntTy::I16), InferSigned(i)) => Ok(I16(i as i16)),
887         (&ty::TyInt(IntTy::I32), InferSigned(i)) => Ok(I32(i as i32)),
888         (&ty::TyInt(IntTy::I64), InferSigned(i)) => Ok(I64(i as i64)),
889         (&ty::TyInt(IntTy::I128), InferSigned(i)) => Ok(I128(i)),
890         (&ty::TyInt(IntTy::Is), InferSigned(i)) => {
891             Ok(Isize(ConstIsize::new_truncating(i, tcx.sess.target.int_type)))
892         },
893
894         (&ty::TyUint(UintTy::U8), Infer(i)) => Ok(U8(i as u8)),
895         (&ty::TyUint(UintTy::U16), Infer(i)) => Ok(U16(i as u16)),
896         (&ty::TyUint(UintTy::U32), Infer(i)) => Ok(U32(i as u32)),
897         (&ty::TyUint(UintTy::U64), Infer(i)) => Ok(U64(i as u64)),
898         (&ty::TyUint(UintTy::U128), Infer(i)) => Ok(U128(i)),
899         (&ty::TyUint(UintTy::Us), Infer(i)) => {
900             Ok(Usize(ConstUsize::new_truncating(i, tcx.sess.target.uint_type)))
901         },
902         (&ty::TyUint(_), InferSigned(_)) => Err(IntermediateUnsignedNegative),
903
904         (&ty::TyInt(ity), i) => Err(TypeMismatch(ity.to_string(), i)),
905         (&ty::TyUint(ity), i) => Err(TypeMismatch(ity.to_string(), i)),
906
907         (&ty::TyAdt(adt, _), i) if adt.is_enum() => {
908             let hints = tcx.lookup_repr_hints(adt.did);
909             let int_ty = tcx.enum_repr_type(hints.iter().next());
910             infer(i, tcx, &int_ty.to_ty(tcx).sty)
911         },
912         (_, i) => Err(BadType(ConstVal::Integral(i))),
913     }
914 }
915
916 fn resolve_trait_associated_const<'a, 'tcx: 'a>(
917     tcx: TyCtxt<'a, 'tcx, 'tcx>,
918     trait_item_id: DefId,
919     default_value: Option<(&'tcx Expr, Option<&'a ty::TypeckTables<'tcx>>, Option<ty::Ty<'tcx>>)>,
920     trait_id: DefId,
921     rcvr_substs: &'tcx Substs<'tcx>
922 ) -> Option<(&'tcx Expr, Option<&'a ty::TypeckTables<'tcx>>, Option<ty::Ty<'tcx>>)>
923 {
924     let trait_ref = ty::Binder(ty::TraitRef::new(trait_id, rcvr_substs));
925     debug!("resolve_trait_associated_const: trait_ref={:?}",
926            trait_ref);
927
928     tcx.populate_implementations_for_trait_if_necessary(trait_id);
929     tcx.infer_ctxt((), Reveal::NotSpecializable).enter(|infcx| {
930         let mut selcx = traits::SelectionContext::new(&infcx);
931         let obligation = traits::Obligation::new(traits::ObligationCause::dummy(),
932                                                  trait_ref.to_poly_trait_predicate());
933         let selection = match selcx.select(&obligation) {
934             Ok(Some(vtable)) => vtable,
935             // Still ambiguous, so give up and let the caller decide whether this
936             // expression is really needed yet. Some associated constant values
937             // can't be evaluated until monomorphization is done in trans.
938             Ok(None) => {
939                 return None
940             }
941             Err(_) => {
942                 return None
943             }
944         };
945
946         // NOTE: this code does not currently account for specialization, but when
947         // it does so, it should hook into the Reveal to determine when the
948         // constant should resolve; this will also require plumbing through to this
949         // function whether we are in "trans mode" to pick the right Reveal
950         // when constructing the inference context above.
951         match selection {
952             traits::VtableImpl(ref impl_data) => {
953                 let name = tcx.associated_item(trait_item_id).name;
954                 let ac = tcx.associated_items(impl_data.impl_def_id)
955                     .find(|item| item.kind == ty::AssociatedKind::Const && item.name == name);
956                 match ac {
957                     Some(ic) => lookup_const_by_id(tcx, ic.def_id, None),
958                     None => default_value,
959                 }
960             }
961             _ => {
962                 bug!("resolve_trait_associated_const: unexpected vtable type")
963             }
964         }
965     })
966 }
967
968 fn cast_const_int<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, val: ConstInt, ty: ty::Ty) -> CastResult {
969     let v = val.to_u128_unchecked();
970     match ty.sty {
971         ty::TyBool if v == 0 => Ok(Bool(false)),
972         ty::TyBool if v == 1 => Ok(Bool(true)),
973         ty::TyInt(ast::IntTy::I8) => Ok(Integral(I8(v as i128 as i8))),
974         ty::TyInt(ast::IntTy::I16) => Ok(Integral(I16(v as i128 as i16))),
975         ty::TyInt(ast::IntTy::I32) => Ok(Integral(I32(v as i128 as i32))),
976         ty::TyInt(ast::IntTy::I64) => Ok(Integral(I64(v as i128 as i64))),
977         ty::TyInt(ast::IntTy::I128) => Ok(Integral(I128(v as i128))),
978         ty::TyInt(ast::IntTy::Is) => {
979             Ok(Integral(Isize(ConstIsize::new_truncating(v as i128, tcx.sess.target.int_type))))
980         },
981         ty::TyUint(ast::UintTy::U8) => Ok(Integral(U8(v as u8))),
982         ty::TyUint(ast::UintTy::U16) => Ok(Integral(U16(v as u16))),
983         ty::TyUint(ast::UintTy::U32) => Ok(Integral(U32(v as u32))),
984         ty::TyUint(ast::UintTy::U64) => Ok(Integral(U64(v as u64))),
985         ty::TyUint(ast::UintTy::U128) => Ok(Integral(U128(v as u128))),
986         ty::TyUint(ast::UintTy::Us) => {
987             Ok(Integral(Usize(ConstUsize::new_truncating(v, tcx.sess.target.uint_type))))
988         },
989         ty::TyFloat(ast::FloatTy::F64) => match val.erase_type() {
990             Infer(u) => Ok(Float(F64(u as f64))),
991             InferSigned(i) => Ok(Float(F64(i as f64))),
992             _ => bug!("ConstInt::erase_type returned something other than Infer/InferSigned"),
993         },
994         ty::TyFloat(ast::FloatTy::F32) => match val.erase_type() {
995             Infer(u) => Ok(Float(F32(u as f32))),
996             InferSigned(i) => Ok(Float(F32(i as f32))),
997             _ => bug!("ConstInt::erase_type returned something other than Infer/InferSigned"),
998         },
999         ty::TyRawPtr(_) => Err(ErrKind::UnimplementedConstVal("casting an address to a raw ptr")),
1000         ty::TyChar => match infer(val, tcx, &ty::TyUint(ast::UintTy::U8)) {
1001             Ok(U8(u)) => Ok(Char(u as char)),
1002             // can only occur before typeck, typeck blocks `T as char` for `T` != `u8`
1003             _ => Err(CharCast(val)),
1004         },
1005         _ => Err(CannotCast),
1006     }
1007 }
1008
1009 fn cast_const_float<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1010                               val: ConstFloat,
1011                               ty: ty::Ty) -> CastResult {
1012     match ty.sty {
1013         ty::TyInt(_) | ty::TyUint(_) => {
1014             let i = match val {
1015                 F32(f) if f >= 0.0 => Infer(f as u128),
1016                 FInfer { f64: f, .. } |
1017                 F64(f) if f >= 0.0 => Infer(f as u128),
1018
1019                 F32(f) => InferSigned(f as i128),
1020                 FInfer { f64: f, .. } |
1021                 F64(f) => InferSigned(f as i128)
1022             };
1023
1024             if let (InferSigned(_), &ty::TyUint(_)) = (i, &ty.sty) {
1025                 return Err(CannotCast);
1026             }
1027
1028             cast_const_int(tcx, i, ty)
1029         }
1030         ty::TyFloat(ast::FloatTy::F64) => Ok(Float(F64(match val {
1031             F32(f) => f as f64,
1032             FInfer { f64: f, .. } | F64(f) => f
1033         }))),
1034         ty::TyFloat(ast::FloatTy::F32) => Ok(Float(F32(match val {
1035             F64(f) => f as f32,
1036             FInfer { f32: f, .. } | F32(f) => f
1037         }))),
1038         _ => Err(CannotCast),
1039     }
1040 }
1041
1042 fn cast_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, val: ConstVal, ty: ty::Ty) -> CastResult {
1043     match val {
1044         Integral(i) => cast_const_int(tcx, i, ty),
1045         Bool(b) => cast_const_int(tcx, Infer(b as u128), ty),
1046         Float(f) => cast_const_float(tcx, f, ty),
1047         Char(c) => cast_const_int(tcx, Infer(c as u128), ty),
1048         Function(_) => Err(UnimplementedConstVal("casting fn pointers")),
1049         ByteStr(b) => match ty.sty {
1050             ty::TyRawPtr(_) => {
1051                 Err(ErrKind::UnimplementedConstVal("casting a bytestr to a raw ptr"))
1052             },
1053             ty::TyRef(_, ty::TypeAndMut { ref ty, mutbl: hir::MutImmutable }) => match ty.sty {
1054                 ty::TyArray(ty, n) if ty == tcx.types.u8 && n == b.len() => Ok(ByteStr(b)),
1055                 ty::TySlice(_) => {
1056                     Err(ErrKind::UnimplementedConstVal("casting a bytestr to slice"))
1057                 },
1058                 _ => Err(CannotCast),
1059             },
1060             _ => Err(CannotCast),
1061         },
1062         Str(s) => match ty.sty {
1063             ty::TyRawPtr(_) => Err(ErrKind::UnimplementedConstVal("casting a str to a raw ptr")),
1064             ty::TyRef(_, ty::TypeAndMut { ref ty, mutbl: hir::MutImmutable }) => match ty.sty {
1065                 ty::TyStr => Ok(Str(s)),
1066                 _ => Err(CannotCast),
1067             },
1068             _ => Err(CannotCast),
1069         },
1070         _ => Err(CannotCast),
1071     }
1072 }
1073
1074 fn lit_to_const<'a, 'tcx>(lit: &ast::LitKind,
1075                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
1076                           ty_hint: Option<Ty<'tcx>>)
1077                           -> Result<ConstVal, ErrKind> {
1078     use syntax::ast::*;
1079     use syntax::ast::LitIntType::*;
1080     match *lit {
1081         LitKind::Str(ref s, _) => Ok(Str(s.as_str())),
1082         LitKind::ByteStr(ref data) => Ok(ByteStr(data.clone())),
1083         LitKind::Byte(n) => Ok(Integral(U8(n))),
1084         LitKind::Int(n, Signed(ity)) => {
1085             infer(InferSigned(n as i128), tcx, &ty::TyInt(ity)).map(Integral)
1086         },
1087
1088         // FIXME: this should become u128.
1089         LitKind::Int(n, Unsuffixed) => {
1090             match ty_hint.map(|t| &t.sty) {
1091                 Some(&ty::TyInt(ity)) => {
1092                     infer(InferSigned(n as i128), tcx, &ty::TyInt(ity)).map(Integral)
1093                 },
1094                 Some(&ty::TyUint(uty)) => {
1095                     infer(Infer(n as u128), tcx, &ty::TyUint(uty)).map(Integral)
1096                 },
1097                 None => Ok(Integral(Infer(n as u128))),
1098                 Some(&ty::TyAdt(adt, _)) => {
1099                     let hints = tcx.lookup_repr_hints(adt.did);
1100                     let int_ty = tcx.enum_repr_type(hints.iter().next());
1101                     infer(Infer(n as u128), tcx, &int_ty.to_ty(tcx).sty).map(Integral)
1102                 },
1103                 Some(ty_hint) => bug!("bad ty_hint: {:?}, {:?}", ty_hint, lit),
1104             }
1105         },
1106         LitKind::Int(n, Unsigned(ity)) => {
1107             infer(Infer(n as u128), tcx, &ty::TyUint(ity)).map(Integral)
1108         },
1109
1110         LitKind::Float(n, fty) => {
1111             parse_float(&n.as_str(), Some(fty)).map(Float)
1112         }
1113         LitKind::FloatUnsuffixed(n) => {
1114             let fty_hint = match ty_hint.map(|t| &t.sty) {
1115                 Some(&ty::TyFloat(fty)) => Some(fty),
1116                 _ => None
1117             };
1118             parse_float(&n.as_str(), fty_hint).map(Float)
1119         }
1120         LitKind::Bool(b) => Ok(Bool(b)),
1121         LitKind::Char(c) => Ok(Char(c)),
1122     }
1123 }
1124
1125 fn parse_float(num: &str, fty_hint: Option<ast::FloatTy>)
1126                -> Result<ConstFloat, ErrKind> {
1127     let val = match fty_hint {
1128         Some(ast::FloatTy::F32) => num.parse::<f32>().map(F32),
1129         Some(ast::FloatTy::F64) => num.parse::<f64>().map(F64),
1130         None => {
1131             num.parse::<f32>().and_then(|f32| {
1132                 num.parse::<f64>().map(|f64| {
1133                     FInfer { f32: f32, f64: f64 }
1134                 })
1135             })
1136         }
1137     };
1138     val.map_err(|_| {
1139         // FIXME(#31407) this is only necessary because float parsing is buggy
1140         UnimplementedConstVal("could not evaluate float literal (see issue #31407)")
1141     })
1142 }
1143
1144 pub fn compare_const_vals(tcx: TyCtxt, span: Span, a: &ConstVal, b: &ConstVal)
1145                           -> Result<Ordering, ErrorReported>
1146 {
1147     let result = match (a, b) {
1148         (&Integral(a), &Integral(b)) => a.try_cmp(b).ok(),
1149         (&Float(a), &Float(b)) => a.try_cmp(b).ok(),
1150         (&Str(ref a), &Str(ref b)) => Some(a.cmp(b)),
1151         (&Bool(a), &Bool(b)) => Some(a.cmp(&b)),
1152         (&ByteStr(ref a), &ByteStr(ref b)) => Some(a.cmp(b)),
1153         (&Char(a), &Char(ref b)) => Some(a.cmp(b)),
1154         _ => None,
1155     };
1156
1157     match result {
1158         Some(result) => Ok(result),
1159         None => {
1160             // FIXME: can this ever be reached?
1161             span_err!(tcx.sess, span, E0298,
1162                       "type mismatch comparing {} and {}",
1163                       a.description(),
1164                       b.description());
1165             Err(ErrorReported)
1166         }
1167     }
1168 }
1169
1170 impl<'a, 'tcx> ConstContext<'a, 'tcx> {
1171     pub fn compare_lit_exprs(&self,
1172                              span: Span,
1173                              a: &Expr,
1174                              b: &Expr) -> Result<Ordering, ErrorReported> {
1175         let tcx = self.tcx;
1176         let a = match self.eval(a, ExprTypeChecked) {
1177             Ok(a) => a,
1178             Err(e) => {
1179                 report_const_eval_err(tcx, &e, a.span, "expression").emit();
1180                 return Err(ErrorReported);
1181             }
1182         };
1183         let b = match self.eval(b, ExprTypeChecked) {
1184             Ok(b) => b,
1185             Err(e) => {
1186                 report_const_eval_err(tcx, &e, b.span, "expression").emit();
1187                 return Err(ErrorReported);
1188             }
1189         };
1190         compare_const_vals(tcx, span, &a, &b)
1191     }
1192 }
1193
1194
1195 /// Returns the value of the length-valued expression
1196 pub fn eval_length<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1197                              count: hir::BodyId,
1198                              reason: &str)
1199                              -> Result<usize, ErrorReported>
1200 {
1201     let hint = UncheckedExprHint(tcx.types.usize);
1202     let count_expr = &tcx.hir.body(count).value;
1203     match ConstContext::new(tcx, count).eval(count_expr, hint) {
1204         Ok(Integral(Usize(count))) => {
1205             let val = count.as_u64(tcx.sess.target.uint_type);
1206             assert_eq!(val as usize as u64, val);
1207             Ok(val as usize)
1208         },
1209         Ok(const_val) => {
1210             struct_span_err!(tcx.sess, count_expr.span, E0306,
1211                              "expected `usize` for {}, found {}",
1212                              reason,
1213                              const_val.description())
1214                 .span_label(count_expr.span, &format!("expected `usize`"))
1215                 .emit();
1216
1217             Err(ErrorReported)
1218         }
1219         Err(err) => {
1220             let mut diag = report_const_eval_err(
1221                 tcx, &err, count_expr.span, reason);
1222
1223             if let hir::ExprPath(hir::QPath::Resolved(None, ref path)) = count_expr.node {
1224                 if let Def::Local(..) = path.def {
1225                     diag.note(&format!("`{}` is a variable",
1226                                        tcx.hir.node_to_pretty_string(count_expr.id)));
1227                 }
1228             }
1229
1230             diag.emit();
1231             Err(ErrorReported)
1232         }
1233     }
1234 }