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