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