]> git.lizzy.rs Git - rust.git/blob - src/librustc_const_eval/eval.rs
Rollup merge of #39426 - jakllsch:netbsd-c, 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(I128_OVERFLOW, _), Some(&ty::TyInt(IntTy::I128))) |
486                 (&LitKind::Int(I128_OVERFLOW, Signed(IntTy::I128)), _) => {
487                     return Ok(Integral(I128(i128::min_value())))
488                 },
489                 (&LitKind::Int(n, _), Some(&ty::TyInt(IntTy::Is))) |
490                 (&LitKind::Int(n, Signed(IntTy::Is)), _) => {
491                     match tcx.sess.target.int_type {
492                         IntTy::I16 => if n == I16_OVERFLOW {
493                             return Ok(Integral(Isize(Is16(i16::min_value()))));
494                         },
495                         IntTy::I32 => if n == I32_OVERFLOW {
496                             return Ok(Integral(Isize(Is32(i32::min_value()))));
497                         },
498                         IntTy::I64 => if n == I64_OVERFLOW {
499                             return Ok(Integral(Isize(Is64(i64::min_value()))));
500                         },
501                         _ => bug!(),
502                     }
503                 },
504                 _ => {},
505             }
506         }
507         match cx.eval(inner, ty_hint)? {
508           Float(f) => Float(-f),
509           Integral(i) => Integral(math!(e, -i)),
510           const_val => signal!(e, NegateOn(const_val)),
511         }
512       }
513       hir::ExprUnary(hir::UnNot, ref inner) => {
514         match cx.eval(inner, ty_hint)? {
515           Integral(i) => Integral(math!(e, !i)),
516           Bool(b) => Bool(!b),
517           const_val => signal!(e, NotOn(const_val)),
518         }
519       }
520       hir::ExprUnary(hir::UnDeref, _) => signal!(e, UnimplementedConstVal("deref operation")),
521       hir::ExprBinary(op, ref a, ref b) => {
522         let b_ty = match op.node {
523             hir::BiShl | hir::BiShr => ty_hint.erase_hint(),
524             _ => ty_hint
525         };
526         // technically, if we don't have type hints, but integral eval
527         // gives us a type through a type-suffix, cast or const def type
528         // we need to re-eval the other value of the BinOp if it was
529         // not inferred
530         match (cx.eval(a, ty_hint)?,
531                cx.eval(b, b_ty)?) {
532           (Float(a), Float(b)) => {
533             use std::cmp::Ordering::*;
534             match op.node {
535               hir::BiAdd => Float(math!(e, a + b)),
536               hir::BiSub => Float(math!(e, a - b)),
537               hir::BiMul => Float(math!(e, a * b)),
538               hir::BiDiv => Float(math!(e, a / b)),
539               hir::BiRem => Float(math!(e, a % b)),
540               hir::BiEq => Bool(math!(e, a.try_cmp(b)) == Equal),
541               hir::BiLt => Bool(math!(e, a.try_cmp(b)) == Less),
542               hir::BiLe => Bool(math!(e, a.try_cmp(b)) != Greater),
543               hir::BiNe => Bool(math!(e, a.try_cmp(b)) != Equal),
544               hir::BiGe => Bool(math!(e, a.try_cmp(b)) != Less),
545               hir::BiGt => Bool(math!(e, a.try_cmp(b)) == Greater),
546               _ => signal!(e, InvalidOpForFloats(op.node)),
547             }
548           }
549           (Integral(a), Integral(b)) => {
550             use std::cmp::Ordering::*;
551             match op.node {
552               hir::BiAdd => Integral(math!(e, a + b)),
553               hir::BiSub => Integral(math!(e, a - b)),
554               hir::BiMul => Integral(math!(e, a * b)),
555               hir::BiDiv => Integral(math!(e, a / b)),
556               hir::BiRem => Integral(math!(e, a % b)),
557               hir::BiBitAnd => Integral(math!(e, a & b)),
558               hir::BiBitOr => Integral(math!(e, a | b)),
559               hir::BiBitXor => Integral(math!(e, a ^ b)),
560               hir::BiShl => Integral(math!(e, a << b)),
561               hir::BiShr => Integral(math!(e, a >> b)),
562               hir::BiEq => Bool(math!(e, a.try_cmp(b)) == Equal),
563               hir::BiLt => Bool(math!(e, a.try_cmp(b)) == Less),
564               hir::BiLe => Bool(math!(e, a.try_cmp(b)) != Greater),
565               hir::BiNe => Bool(math!(e, a.try_cmp(b)) != Equal),
566               hir::BiGe => Bool(math!(e, a.try_cmp(b)) != Less),
567               hir::BiGt => Bool(math!(e, a.try_cmp(b)) == Greater),
568               _ => signal!(e, InvalidOpForInts(op.node)),
569             }
570           }
571           (Bool(a), Bool(b)) => {
572             Bool(match op.node {
573               hir::BiAnd => a && b,
574               hir::BiOr => a || b,
575               hir::BiBitXor => a ^ b,
576               hir::BiBitAnd => a & b,
577               hir::BiBitOr => a | b,
578               hir::BiEq => a == b,
579               hir::BiNe => a != b,
580               hir::BiLt => a < b,
581               hir::BiLe => a <= b,
582               hir::BiGe => a >= b,
583               hir::BiGt => a > b,
584               _ => signal!(e, InvalidOpForBools(op.node)),
585              })
586           }
587
588           _ => signal!(e, MiscBinaryOp),
589         }
590       }
591       hir::ExprCast(ref base, ref target_ty) => {
592         let ety = tcx.ast_ty_to_prim_ty(&target_ty).or(ety)
593                 .unwrap_or_else(|| {
594                     tcx.sess.span_fatal(target_ty.span,
595                                         "target type not found for const cast")
596                 });
597
598         let base_hint = if let ExprTypeChecked = ty_hint {
599             ExprTypeChecked
600         } else {
601             match cx.tables.and_then(|tables| tables.expr_ty_opt(&base)) {
602                 Some(t) => UncheckedExprHint(t),
603                 None => ty_hint
604             }
605         };
606
607         let val = match cx.eval(base, base_hint) {
608             Ok(val) => val,
609             Err(ConstEvalErr { kind: ErroneousReferencedConstant(
610                 box ConstEvalErr { kind: TypeMismatch(_, val), .. }), .. }) |
611             Err(ConstEvalErr { kind: TypeMismatch(_, val), .. }) => {
612                 // Something like `5i8 as usize` doesn't need a type hint for the base
613                 // instead take the type hint from the inner value
614                 let hint = match val.int_type() {
615                     Some(IntType::UnsignedInt(ty)) => ty_hint.checked_or(tcx.mk_mach_uint(ty)),
616                     Some(IntType::SignedInt(ty)) => ty_hint.checked_or(tcx.mk_mach_int(ty)),
617                     // we had a type hint, so we can't have an unknown type
618                     None => bug!(),
619                 };
620                 cx.eval(base, hint)?
621             },
622             Err(e) => return Err(e),
623         };
624         match cast_const(tcx, val, ety) {
625             Ok(val) => val,
626             Err(kind) => return Err(ConstEvalErr { span: e.span, kind: kind }),
627         }
628       }
629       hir::ExprPath(ref qpath) => {
630           let def = cx.tables.map(|tables| tables.qpath_def(qpath, e.id)).unwrap_or_else(|| {
631             // There are no tables so we can only handle already-resolved HIR.
632             match *qpath {
633                 hir::QPath::Resolved(_, ref path) => path.def,
634                 hir::QPath::TypeRelative(..) => Def::Err
635             }
636           });
637           match def {
638               Def::Const(def_id) |
639               Def::AssociatedConst(def_id) => {
640                   let substs = if let ExprTypeChecked = ty_hint {
641                       Some(cx.tables.and_then(|tables| tables.node_id_item_substs(e.id))
642                         .unwrap_or_else(|| tcx.intern_substs(&[])))
643                   } else {
644                       None
645                   };
646                   if let Some((expr, tables, ty)) = lookup_const_by_id(tcx, def_id, substs) {
647                       let item_hint = match ty {
648                           Some(ty) => ty_hint.checked_or(ty),
649                           None => ty_hint,
650                       };
651                       let cx = ConstContext { tcx: tcx, tables: tables, fn_args: None };
652                       match cx.eval(expr, item_hint) {
653                           Ok(val) => val,
654                           Err(err) => {
655                               debug!("bad reference: {:?}, {:?}", err.description(), err.span);
656                               signal!(e, ErroneousReferencedConstant(box err))
657                           },
658                       }
659                   } else {
660                       signal!(e, NonConstPath);
661                   }
662               },
663               Def::VariantCtor(variant_def, ..) => {
664                   if let Some((expr, tables)) = lookup_variant_by_id(tcx, variant_def) {
665                       let cx = ConstContext { tcx: tcx, tables: tables, fn_args: None };
666                       match cx.eval(expr, ty_hint) {
667                           Ok(val) => val,
668                           Err(err) => {
669                               debug!("bad reference: {:?}, {:?}", err.description(), err.span);
670                               signal!(e, ErroneousReferencedConstant(box err))
671                           },
672                       }
673                   } else {
674                       signal!(e, UnimplementedConstVal("enum variants"));
675                   }
676               }
677               Def::StructCtor(..) => {
678                   ConstVal::Struct(Default::default())
679               }
680               Def::Local(def_id) => {
681                   debug!("Def::Local({:?}): {:?}", def_id, cx.fn_args);
682                   if let Some(val) = cx.fn_args.as_ref().and_then(|args| args.get(&def_id)) {
683                       val.clone()
684                   } else {
685                       signal!(e, NonConstPath);
686                   }
687               },
688               Def::Method(id) | Def::Fn(id) => Function(id),
689               Def::Err => signal!(e, UnresolvedPath),
690               _ => signal!(e, NonConstPath),
691           }
692       }
693       hir::ExprCall(ref callee, ref args) => {
694           let sub_ty_hint = ty_hint.erase_hint();
695           let callee_val = cx.eval(callee, sub_ty_hint)?;
696           let did = match callee_val {
697               Function(did) => did,
698               Struct(_) => signal!(e, UnimplementedConstVal("tuple struct constructors")),
699               callee => signal!(e, CallOn(callee)),
700           };
701           let (body, tables) = match lookup_const_fn_by_id(tcx, did) {
702               Some(x) => x,
703               None => signal!(e, NonConstPath),
704           };
705
706           let arg_defs = body.arguments.iter().map(|arg| match arg.pat.node {
707                hir::PatKind::Binding(_, def_id, _, _) => Some(def_id),
708                _ => None
709            }).collect::<Vec<_>>();
710           assert_eq!(arg_defs.len(), args.len());
711
712           let mut call_args = DefIdMap();
713           for (arg, arg_expr) in arg_defs.into_iter().zip(args.iter()) {
714               let arg_hint = ty_hint.erase_hint();
715               let arg_val = cx.eval(arg_expr, arg_hint)?;
716               debug!("const call arg: {:?}", arg);
717               if let Some(def_id) = arg {
718                 assert!(call_args.insert(def_id, arg_val).is_none());
719               }
720           }
721           debug!("const call({:?})", call_args);
722           let callee_cx = ConstContext {
723             tcx: tcx,
724             tables: tables,
725             fn_args: Some(call_args)
726           };
727           callee_cx.eval(&body.value, ty_hint)?
728       },
729       hir::ExprLit(ref lit) => match lit_to_const(&lit.node, tcx, ety) {
730           Ok(val) => val,
731           Err(err) => signal!(e, err),
732       },
733       hir::ExprBlock(ref block) => {
734         match block.expr {
735             Some(ref expr) => cx.eval(expr, ty_hint)?,
736             None => signal!(e, UnimplementedConstVal("empty block")),
737         }
738       }
739       hir::ExprType(ref e, _) => cx.eval(e, ty_hint)?,
740       hir::ExprTup(ref fields) => {
741         let field_hint = ty_hint.erase_hint();
742         Tuple(fields.iter().map(|e| cx.eval(e, field_hint)).collect::<Result<_, _>>()?)
743       }
744       hir::ExprStruct(_, ref fields, _) => {
745         let field_hint = ty_hint.erase_hint();
746         Struct(fields.iter().map(|f| {
747             cx.eval(&f.expr, field_hint).map(|v| (f.name.node, v))
748         }).collect::<Result<_, _>>()?)
749       }
750       hir::ExprIndex(ref arr, ref idx) => {
751         if !tcx.sess.features.borrow().const_indexing {
752             signal!(e, IndexOpFeatureGated);
753         }
754         let arr_hint = ty_hint.erase_hint();
755         let arr = cx.eval(arr, arr_hint)?;
756         let idx_hint = ty_hint.checked_or(tcx.types.usize);
757         let idx = match cx.eval(idx, idx_hint)? {
758             Integral(Usize(i)) => i.as_u64(tcx.sess.target.uint_type),
759             Integral(_) => bug!(),
760             _ => signal!(idx, IndexNotInt),
761         };
762         assert_eq!(idx as usize as u64, idx);
763         match arr {
764             Array(ref v) => {
765                 if let Some(elem) = v.get(idx as usize) {
766                     elem.clone()
767                 } else {
768                     let n = v.len() as u64;
769                     assert_eq!(n as usize as u64, n);
770                     signal!(e, IndexOutOfBounds { len: n, index: idx })
771                 }
772             }
773
774             Repeat(.., n) if idx >= n => {
775                 signal!(e, IndexOutOfBounds { len: n, index: idx })
776             }
777             Repeat(ref elem, _) => (**elem).clone(),
778
779             ByteStr(ref data) if idx >= data.len() as u64 => {
780                 signal!(e, IndexOutOfBounds { len: data.len() as u64, index: idx })
781             }
782             ByteStr(data) => {
783                 Integral(U8(data[idx as usize]))
784             },
785
786             _ => signal!(e, IndexedNonVec),
787         }
788       }
789       hir::ExprArray(ref v) => {
790         let elem_hint = ty_hint.erase_hint();
791         Array(v.iter().map(|e| cx.eval(e, elem_hint)).collect::<Result<_, _>>()?)
792       }
793       hir::ExprRepeat(ref elem, count) => {
794           let elem_hint = ty_hint.erase_hint();
795           let len_hint = ty_hint.checked_or(tcx.types.usize);
796           let n = if let Some(ty) = ety {
797             // For cross-crate constants, we have the type already,
798             // but not the body for `count`, so use the type.
799             match ty.sty {
800                 ty::TyArray(_, n) => n as u64,
801                 _ => bug!()
802             }
803           } else {
804             let n = &tcx.hir.body(count).value;
805             match ConstContext::new(tcx, count).eval(n, len_hint)? {
806                 Integral(Usize(i)) => i.as_u64(tcx.sess.target.uint_type),
807                 Integral(_) => signal!(e, RepeatCountNotNatural),
808                 _ => signal!(e, RepeatCountNotInt),
809             }
810           };
811           Repeat(Box::new(cx.eval(elem, elem_hint)?), n)
812       },
813       hir::ExprTupField(ref base, index) => {
814         let base_hint = ty_hint.erase_hint();
815         let c = cx.eval(base, base_hint)?;
816         if let Tuple(ref fields) = c {
817             if let Some(elem) = fields.get(index.node) {
818                 elem.clone()
819             } else {
820                 signal!(e, TupleIndexOutOfBounds);
821             }
822         } else {
823             signal!(base, ExpectedConstTuple);
824         }
825       }
826       hir::ExprField(ref base, field_name) => {
827         let base_hint = ty_hint.erase_hint();
828         let c = cx.eval(base, base_hint)?;
829         if let Struct(ref fields) = c {
830             if let Some(f) = fields.get(&field_name.node) {
831                 f.clone()
832             } else {
833                 signal!(e, MissingStructField);
834             }
835         } else {
836             signal!(base, ExpectedConstStruct);
837         }
838       }
839       hir::ExprAddrOf(..) => signal!(e, UnimplementedConstVal("address operator")),
840       _ => signal!(e, MiscCatchAll)
841     };
842
843     match (ety.map(|t| &t.sty), result) {
844         (Some(ref ty_hint), Integral(i)) => match infer(i, tcx, ty_hint) {
845             Ok(inferred) => Ok(Integral(inferred)),
846             Err(err) => signal!(e, err),
847         },
848         (_, result) => Ok(result),
849     }
850 }
851
852 fn infer<'a, 'tcx>(i: ConstInt,
853                    tcx: TyCtxt<'a, 'tcx, 'tcx>,
854                    ty_hint: &ty::TypeVariants<'tcx>)
855                    -> Result<ConstInt, ErrKind> {
856     use syntax::ast::*;
857
858     match (ty_hint, i) {
859         (&ty::TyInt(IntTy::I8), result @ I8(_)) => Ok(result),
860         (&ty::TyInt(IntTy::I16), result @ I16(_)) => Ok(result),
861         (&ty::TyInt(IntTy::I32), result @ I32(_)) => Ok(result),
862         (&ty::TyInt(IntTy::I64), result @ I64(_)) => Ok(result),
863         (&ty::TyInt(IntTy::I128), result @ I128(_)) => Ok(result),
864         (&ty::TyInt(IntTy::Is), result @ Isize(_)) => Ok(result),
865
866         (&ty::TyUint(UintTy::U8), result @ U8(_)) => Ok(result),
867         (&ty::TyUint(UintTy::U16), result @ U16(_)) => Ok(result),
868         (&ty::TyUint(UintTy::U32), result @ U32(_)) => Ok(result),
869         (&ty::TyUint(UintTy::U64), result @ U64(_)) => Ok(result),
870         (&ty::TyUint(UintTy::U128), result @ U128(_)) => Ok(result),
871         (&ty::TyUint(UintTy::Us), result @ Usize(_)) => Ok(result),
872
873         (&ty::TyInt(IntTy::I8), Infer(i)) => Ok(I8(i as i128 as i8)),
874         (&ty::TyInt(IntTy::I16), Infer(i)) => Ok(I16(i as i128 as i16)),
875         (&ty::TyInt(IntTy::I32), Infer(i)) => Ok(I32(i as i128 as i32)),
876         (&ty::TyInt(IntTy::I64), Infer(i)) => Ok(I64(i as i128 as i64)),
877         (&ty::TyInt(IntTy::I128), Infer(i)) => Ok(I128(i as i128)),
878         (&ty::TyInt(IntTy::Is), Infer(i)) => {
879             Ok(Isize(ConstIsize::new_truncating(i as i128, tcx.sess.target.int_type)))
880         },
881
882         (&ty::TyInt(IntTy::I8), InferSigned(i)) => Ok(I8(i as i8)),
883         (&ty::TyInt(IntTy::I16), InferSigned(i)) => Ok(I16(i as i16)),
884         (&ty::TyInt(IntTy::I32), InferSigned(i)) => Ok(I32(i as i32)),
885         (&ty::TyInt(IntTy::I64), InferSigned(i)) => Ok(I64(i as i64)),
886         (&ty::TyInt(IntTy::I128), InferSigned(i)) => Ok(I128(i)),
887         (&ty::TyInt(IntTy::Is), InferSigned(i)) => {
888             Ok(Isize(ConstIsize::new_truncating(i, tcx.sess.target.int_type)))
889         },
890
891         (&ty::TyUint(UintTy::U8), Infer(i)) => Ok(U8(i as u8)),
892         (&ty::TyUint(UintTy::U16), Infer(i)) => Ok(U16(i as u16)),
893         (&ty::TyUint(UintTy::U32), Infer(i)) => Ok(U32(i as u32)),
894         (&ty::TyUint(UintTy::U64), Infer(i)) => Ok(U64(i as u64)),
895         (&ty::TyUint(UintTy::U128), Infer(i)) => Ok(U128(i)),
896         (&ty::TyUint(UintTy::Us), Infer(i)) => {
897             Ok(Usize(ConstUsize::new_truncating(i, tcx.sess.target.uint_type)))
898         },
899         (&ty::TyUint(_), InferSigned(_)) => Err(IntermediateUnsignedNegative),
900
901         (&ty::TyInt(ity), i) => Err(TypeMismatch(ity.to_string(), i)),
902         (&ty::TyUint(ity), i) => Err(TypeMismatch(ity.to_string(), i)),
903
904         (&ty::TyAdt(adt, _), i) if adt.is_enum() => {
905             let hints = tcx.lookup_repr_hints(adt.did);
906             let int_ty = tcx.enum_repr_type(hints.iter().next());
907             infer(i, tcx, &int_ty.to_ty(tcx).sty)
908         },
909         (_, i) => Err(BadType(ConstVal::Integral(i))),
910     }
911 }
912
913 fn resolve_trait_associated_const<'a, 'tcx: 'a>(
914     tcx: TyCtxt<'a, 'tcx, 'tcx>,
915     trait_item_id: DefId,
916     default_value: Option<(&'tcx Expr, Option<&'a ty::TypeckTables<'tcx>>, Option<ty::Ty<'tcx>>)>,
917     trait_id: DefId,
918     rcvr_substs: &'tcx Substs<'tcx>
919 ) -> Option<(&'tcx Expr, Option<&'a ty::TypeckTables<'tcx>>, Option<ty::Ty<'tcx>>)>
920 {
921     let trait_ref = ty::Binder(ty::TraitRef::new(trait_id, rcvr_substs));
922     debug!("resolve_trait_associated_const: trait_ref={:?}",
923            trait_ref);
924
925     tcx.populate_implementations_for_trait_if_necessary(trait_id);
926     tcx.infer_ctxt((), Reveal::NotSpecializable).enter(|infcx| {
927         let mut selcx = traits::SelectionContext::new(&infcx);
928         let obligation = traits::Obligation::new(traits::ObligationCause::dummy(),
929                                                  trait_ref.to_poly_trait_predicate());
930         let selection = match selcx.select(&obligation) {
931             Ok(Some(vtable)) => vtable,
932             // Still ambiguous, so give up and let the caller decide whether this
933             // expression is really needed yet. Some associated constant values
934             // can't be evaluated until monomorphization is done in trans.
935             Ok(None) => {
936                 return None
937             }
938             Err(_) => {
939                 return None
940             }
941         };
942
943         // NOTE: this code does not currently account for specialization, but when
944         // it does so, it should hook into the Reveal to determine when the
945         // constant should resolve; this will also require plumbing through to this
946         // function whether we are in "trans mode" to pick the right Reveal
947         // when constructing the inference context above.
948         match selection {
949             traits::VtableImpl(ref impl_data) => {
950                 let name = tcx.associated_item(trait_item_id).name;
951                 let ac = tcx.associated_items(impl_data.impl_def_id)
952                     .find(|item| item.kind == ty::AssociatedKind::Const && item.name == name);
953                 match ac {
954                     Some(ic) => lookup_const_by_id(tcx, ic.def_id, None),
955                     None => default_value,
956                 }
957             }
958             _ => {
959                 bug!("resolve_trait_associated_const: unexpected vtable type")
960             }
961         }
962     })
963 }
964
965 fn cast_const_int<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, val: ConstInt, ty: ty::Ty) -> CastResult {
966     let v = val.to_u128_unchecked();
967     match ty.sty {
968         ty::TyBool if v == 0 => Ok(Bool(false)),
969         ty::TyBool if v == 1 => Ok(Bool(true)),
970         ty::TyInt(ast::IntTy::I8) => Ok(Integral(I8(v as i128 as i8))),
971         ty::TyInt(ast::IntTy::I16) => Ok(Integral(I16(v as i128 as i16))),
972         ty::TyInt(ast::IntTy::I32) => Ok(Integral(I32(v as i128 as i32))),
973         ty::TyInt(ast::IntTy::I64) => Ok(Integral(I64(v as i128 as i64))),
974         ty::TyInt(ast::IntTy::I128) => Ok(Integral(I128(v as i128))),
975         ty::TyInt(ast::IntTy::Is) => {
976             Ok(Integral(Isize(ConstIsize::new_truncating(v as i128, tcx.sess.target.int_type))))
977         },
978         ty::TyUint(ast::UintTy::U8) => Ok(Integral(U8(v as u8))),
979         ty::TyUint(ast::UintTy::U16) => Ok(Integral(U16(v as u16))),
980         ty::TyUint(ast::UintTy::U32) => Ok(Integral(U32(v as u32))),
981         ty::TyUint(ast::UintTy::U64) => Ok(Integral(U64(v as u64))),
982         ty::TyUint(ast::UintTy::U128) => Ok(Integral(U128(v as u128))),
983         ty::TyUint(ast::UintTy::Us) => {
984             Ok(Integral(Usize(ConstUsize::new_truncating(v, tcx.sess.target.uint_type))))
985         },
986         ty::TyFloat(ast::FloatTy::F64) => match val.erase_type() {
987             Infer(u) => Ok(Float(F64(u as f64))),
988             InferSigned(i) => Ok(Float(F64(i as f64))),
989             _ => bug!("ConstInt::erase_type returned something other than Infer/InferSigned"),
990         },
991         ty::TyFloat(ast::FloatTy::F32) => match val.erase_type() {
992             Infer(u) => Ok(Float(F32(u as f32))),
993             InferSigned(i) => Ok(Float(F32(i as f32))),
994             _ => bug!("ConstInt::erase_type returned something other than Infer/InferSigned"),
995         },
996         ty::TyRawPtr(_) => Err(ErrKind::UnimplementedConstVal("casting an address to a raw ptr")),
997         ty::TyChar => match infer(val, tcx, &ty::TyUint(ast::UintTy::U8)) {
998             Ok(U8(u)) => Ok(Char(u as char)),
999             // can only occur before typeck, typeck blocks `T as char` for `T` != `u8`
1000             _ => Err(CharCast(val)),
1001         },
1002         _ => Err(CannotCast),
1003     }
1004 }
1005
1006 fn cast_const_float<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1007                               val: ConstFloat,
1008                               ty: ty::Ty) -> CastResult {
1009     match ty.sty {
1010         ty::TyInt(_) | ty::TyUint(_) => {
1011             let i = match val {
1012                 F32(f) if f >= 0.0 => Infer(f as u128),
1013                 FInfer { f64: f, .. } |
1014                 F64(f) if f >= 0.0 => Infer(f as u128),
1015
1016                 F32(f) => InferSigned(f as i128),
1017                 FInfer { f64: f, .. } |
1018                 F64(f) => InferSigned(f as i128)
1019             };
1020
1021             if let (InferSigned(_), &ty::TyUint(_)) = (i, &ty.sty) {
1022                 return Err(CannotCast);
1023             }
1024
1025             cast_const_int(tcx, i, ty)
1026         }
1027         ty::TyFloat(ast::FloatTy::F64) => Ok(Float(F64(match val {
1028             F32(f) => f as f64,
1029             FInfer { f64: f, .. } | F64(f) => f
1030         }))),
1031         ty::TyFloat(ast::FloatTy::F32) => Ok(Float(F32(match val {
1032             F64(f) => f as f32,
1033             FInfer { f32: f, .. } | F32(f) => f
1034         }))),
1035         _ => Err(CannotCast),
1036     }
1037 }
1038
1039 fn cast_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, val: ConstVal, ty: ty::Ty) -> CastResult {
1040     match val {
1041         Integral(i) => cast_const_int(tcx, i, ty),
1042         Bool(b) => cast_const_int(tcx, Infer(b as u128), ty),
1043         Float(f) => cast_const_float(tcx, f, ty),
1044         Char(c) => cast_const_int(tcx, Infer(c as u128), ty),
1045         Function(_) => Err(UnimplementedConstVal("casting fn pointers")),
1046         ByteStr(b) => match ty.sty {
1047             ty::TyRawPtr(_) => {
1048                 Err(ErrKind::UnimplementedConstVal("casting a bytestr to a raw ptr"))
1049             },
1050             ty::TyRef(_, ty::TypeAndMut { ref ty, mutbl: hir::MutImmutable }) => match ty.sty {
1051                 ty::TyArray(ty, n) if ty == tcx.types.u8 && n == b.len() => Ok(ByteStr(b)),
1052                 ty::TySlice(_) => {
1053                     Err(ErrKind::UnimplementedConstVal("casting a bytestr to slice"))
1054                 },
1055                 _ => Err(CannotCast),
1056             },
1057             _ => Err(CannotCast),
1058         },
1059         Str(s) => match ty.sty {
1060             ty::TyRawPtr(_) => Err(ErrKind::UnimplementedConstVal("casting a str to a raw ptr")),
1061             ty::TyRef(_, ty::TypeAndMut { ref ty, mutbl: hir::MutImmutable }) => match ty.sty {
1062                 ty::TyStr => Ok(Str(s)),
1063                 _ => Err(CannotCast),
1064             },
1065             _ => Err(CannotCast),
1066         },
1067         _ => Err(CannotCast),
1068     }
1069 }
1070
1071 fn lit_to_const<'a, 'tcx>(lit: &ast::LitKind,
1072                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
1073                           ty_hint: Option<Ty<'tcx>>)
1074                           -> Result<ConstVal, ErrKind> {
1075     use syntax::ast::*;
1076     use syntax::ast::LitIntType::*;
1077     match *lit {
1078         LitKind::Str(ref s, _) => Ok(Str(s.as_str())),
1079         LitKind::ByteStr(ref data) => Ok(ByteStr(data.clone())),
1080         LitKind::Byte(n) => Ok(Integral(U8(n))),
1081         LitKind::Int(n, Signed(ity)) => {
1082             infer(InferSigned(n as i128), tcx, &ty::TyInt(ity)).map(Integral)
1083         },
1084
1085         // FIXME: this should become u128.
1086         LitKind::Int(n, Unsuffixed) => {
1087             match ty_hint.map(|t| &t.sty) {
1088                 Some(&ty::TyInt(ity)) => {
1089                     infer(InferSigned(n as i128), tcx, &ty::TyInt(ity)).map(Integral)
1090                 },
1091                 Some(&ty::TyUint(uty)) => {
1092                     infer(Infer(n as u128), tcx, &ty::TyUint(uty)).map(Integral)
1093                 },
1094                 None => Ok(Integral(Infer(n as u128))),
1095                 Some(&ty::TyAdt(adt, _)) => {
1096                     let hints = tcx.lookup_repr_hints(adt.did);
1097                     let int_ty = tcx.enum_repr_type(hints.iter().next());
1098                     infer(Infer(n as u128), tcx, &int_ty.to_ty(tcx).sty).map(Integral)
1099                 },
1100                 Some(ty_hint) => bug!("bad ty_hint: {:?}, {:?}", ty_hint, lit),
1101             }
1102         },
1103         LitKind::Int(n, Unsigned(ity)) => {
1104             infer(Infer(n as u128), tcx, &ty::TyUint(ity)).map(Integral)
1105         },
1106
1107         LitKind::Float(n, fty) => {
1108             parse_float(&n.as_str(), Some(fty)).map(Float)
1109         }
1110         LitKind::FloatUnsuffixed(n) => {
1111             let fty_hint = match ty_hint.map(|t| &t.sty) {
1112                 Some(&ty::TyFloat(fty)) => Some(fty),
1113                 _ => None
1114             };
1115             parse_float(&n.as_str(), fty_hint).map(Float)
1116         }
1117         LitKind::Bool(b) => Ok(Bool(b)),
1118         LitKind::Char(c) => Ok(Char(c)),
1119     }
1120 }
1121
1122 fn parse_float(num: &str, fty_hint: Option<ast::FloatTy>)
1123                -> Result<ConstFloat, ErrKind> {
1124     let val = match fty_hint {
1125         Some(ast::FloatTy::F32) => num.parse::<f32>().map(F32),
1126         Some(ast::FloatTy::F64) => num.parse::<f64>().map(F64),
1127         None => {
1128             num.parse::<f32>().and_then(|f32| {
1129                 num.parse::<f64>().map(|f64| {
1130                     FInfer { f32: f32, f64: f64 }
1131                 })
1132             })
1133         }
1134     };
1135     val.map_err(|_| {
1136         // FIXME(#31407) this is only necessary because float parsing is buggy
1137         UnimplementedConstVal("could not evaluate float literal (see issue #31407)")
1138     })
1139 }
1140
1141 pub fn compare_const_vals(tcx: TyCtxt, span: Span, a: &ConstVal, b: &ConstVal)
1142                           -> Result<Ordering, ErrorReported>
1143 {
1144     let result = match (a, b) {
1145         (&Integral(a), &Integral(b)) => a.try_cmp(b).ok(),
1146         (&Float(a), &Float(b)) => a.try_cmp(b).ok(),
1147         (&Str(ref a), &Str(ref b)) => Some(a.cmp(b)),
1148         (&Bool(a), &Bool(b)) => Some(a.cmp(&b)),
1149         (&ByteStr(ref a), &ByteStr(ref b)) => Some(a.cmp(b)),
1150         (&Char(a), &Char(ref b)) => Some(a.cmp(b)),
1151         _ => None,
1152     };
1153
1154     match result {
1155         Some(result) => Ok(result),
1156         None => {
1157             // FIXME: can this ever be reached?
1158             span_err!(tcx.sess, span, E0298,
1159                       "type mismatch comparing {} and {}",
1160                       a.description(),
1161                       b.description());
1162             Err(ErrorReported)
1163         }
1164     }
1165 }
1166
1167 impl<'a, 'tcx> ConstContext<'a, 'tcx> {
1168     pub fn compare_lit_exprs(&self,
1169                              span: Span,
1170                              a: &Expr,
1171                              b: &Expr) -> Result<Ordering, ErrorReported> {
1172         let tcx = self.tcx;
1173         let a = match self.eval(a, ExprTypeChecked) {
1174             Ok(a) => a,
1175             Err(e) => {
1176                 report_const_eval_err(tcx, &e, a.span, "expression").emit();
1177                 return Err(ErrorReported);
1178             }
1179         };
1180         let b = match self.eval(b, ExprTypeChecked) {
1181             Ok(b) => b,
1182             Err(e) => {
1183                 report_const_eval_err(tcx, &e, b.span, "expression").emit();
1184                 return Err(ErrorReported);
1185             }
1186         };
1187         compare_const_vals(tcx, span, &a, &b)
1188     }
1189 }
1190
1191
1192 /// Returns the value of the length-valued expression
1193 pub fn eval_length<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1194                              count: hir::BodyId,
1195                              reason: &str)
1196                              -> Result<usize, ErrorReported>
1197 {
1198     let hint = UncheckedExprHint(tcx.types.usize);
1199     let count_expr = &tcx.hir.body(count).value;
1200     match ConstContext::new(tcx, count).eval(count_expr, hint) {
1201         Ok(Integral(Usize(count))) => {
1202             let val = count.as_u64(tcx.sess.target.uint_type);
1203             assert_eq!(val as usize as u64, val);
1204             Ok(val as usize)
1205         },
1206         Ok(const_val) => {
1207             struct_span_err!(tcx.sess, count_expr.span, E0306,
1208                              "expected `usize` for {}, found {}",
1209                              reason,
1210                              const_val.description())
1211                 .span_label(count_expr.span, &format!("expected `usize`"))
1212                 .emit();
1213
1214             Err(ErrorReported)
1215         }
1216         Err(err) => {
1217             let mut diag = report_const_eval_err(
1218                 tcx, &err, count_expr.span, reason);
1219
1220             if let hir::ExprPath(hir::QPath::Resolved(None, ref path)) = count_expr.node {
1221                 if let Def::Local(..) = path.def {
1222                     diag.note(&format!("`{}` is a variable",
1223                                        tcx.hir.node_to_pretty_string(count_expr.id)));
1224                 }
1225             }
1226
1227             diag.emit();
1228             Err(ErrorReported)
1229         }
1230     }
1231 }