]> git.lizzy.rs Git - rust.git/blob - src/librustc_const_eval/eval.rs
Rollup merge of #40081 - GuillaumeGomez:poison-docs, r=frewsxcv
[rust.git] / src / librustc_const_eval / eval.rs
1 // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use rustc::middle::const_val::ConstVal::*;
12 use rustc::middle::const_val::ConstVal;
13 use self::ErrKind::*;
14
15 use rustc::hir::map as hir_map;
16 use rustc::hir::map::blocks::FnLikeNode;
17 use rustc::traits;
18 use rustc::hir::def::Def;
19 use rustc::hir::def_id::DefId;
20 use rustc::ty::{self, Ty, TyCtxt};
21 use rustc::ty::util::IntTypeExt;
22 use rustc::ty::subst::{Substs, Subst};
23 use rustc::traits::Reveal;
24 use rustc::util::common::ErrorReported;
25 use rustc::util::nodemap::DefIdMap;
26
27 use graphviz::IntoCow;
28 use syntax::ast;
29 use rustc::hir::{self, Expr};
30 use syntax_pos::{Span, DUMMY_SP};
31
32 use std::borrow::Cow;
33 use std::cmp::Ordering;
34
35 use rustc_const_math::*;
36 use rustc_errors::DiagnosticBuilder;
37
38 macro_rules! signal {
39     ($e:expr, $exn:expr) => {
40         return Err(ConstEvalErr { span: $e.span, kind: $exn })
41     }
42 }
43
44 macro_rules! math {
45     ($e:expr, $op:expr) => {
46         match $op {
47             Ok(val) => val,
48             Err(e) => signal!($e, ErrKind::from(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, &'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(hir_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.item_tables(def_id))
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: &'tcx Substs<'tcx>)
83                                         -> Option<(&'tcx Expr,
84                                                    &'a ty::TypeckTables<'tcx>)> {
85     if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
86         match tcx.hir.find(node_id) {
87             None => None,
88             Some(hir_map::NodeItem(&hir::Item {
89                 node: hir::ItemConst(_, body), ..
90             })) |
91             Some(hir_map::NodeImplItem(&hir::ImplItem {
92                 node: hir::ImplItemKind::Const(_, body), ..
93             })) => {
94                 Some((&tcx.hir.body(body).value,
95                       tcx.item_tables(def_id)))
96             }
97             Some(hir_map::NodeTraitItem(ti)) => match ti.node {
98                 hir::TraitItemKind::Const(_, default) => {
99                     // If we have a trait item and the substitutions for it,
100                     // `resolve_trait_associated_const` will select an impl
101                     // or the default.
102                     let trait_id = tcx.hir.get_parent(node_id);
103                     let trait_id = tcx.hir.local_def_id(trait_id);
104                     let default_value = default.map(|body| {
105                         (&tcx.hir.body(body).value,
106                             tcx.item_tables(def_id))
107                     });
108                     resolve_trait_associated_const(tcx, def_id, default_value, trait_id, substs)
109                 }
110                 _ => None
111             },
112             Some(_) => None
113         }
114     } else {
115         let expr_and_tables = tcx.sess.cstore.maybe_get_item_body(tcx, def_id).map(|body| {
116             (&body.value, tcx.item_tables(def_id))
117         });
118         match tcx.sess.cstore.describe_def(def_id) {
119             Some(Def::AssociatedConst(_)) => {
120                 let trait_id = tcx.sess.cstore.trait_of_item(def_id);
121                 // As mentioned in the comments above for in-crate
122                 // constants, we only try to find the expression for a
123                 // trait-associated const if the caller gives us the
124                 // substitutions for the reference to it.
125                 if let Some(trait_id) = trait_id {
126                     resolve_trait_associated_const(tcx, def_id, expr_and_tables,
127                                                    trait_id, substs)
128                 } else {
129                     expr_and_tables
130                 }
131             },
132             Some(Def::Const(..)) => expr_and_tables,
133             _ => None
134         }
135     }
136 }
137
138 fn lookup_const_fn_by_id<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
139                                    -> Option<(&'tcx hir::Body, &'a ty::TypeckTables<'tcx>)>
140 {
141     if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
142         FnLikeNode::from_node(tcx.hir.get(node_id)).and_then(|fn_like| {
143             if fn_like.constness() == hir::Constness::Const {
144                 Some((tcx.hir.body(fn_like.body()),
145                       tcx.item_tables(def_id)))
146             } else {
147                 None
148             }
149         })
150     } else {
151         if tcx.sess.cstore.is_const_fn(def_id) {
152             tcx.sess.cstore.maybe_get_item_body(tcx, def_id).map(|body| {
153                 (body, tcx.item_tables(def_id))
154             })
155         } else {
156             None
157         }
158     }
159 }
160
161 fn build_const_eval_err<'a, 'tcx>(
162     tcx: TyCtxt<'a, 'tcx, 'tcx>,
163     err: &ConstEvalErr,
164     primary_span: Span,
165     primary_kind: &str)
166     -> DiagnosticBuilder<'tcx>
167 {
168     let mut err = err;
169     while let &ConstEvalErr { kind: ErroneousReferencedConstant(box ref i_err), .. } = err {
170         err = i_err;
171     }
172
173     let mut diag = struct_span_err!(tcx.sess, err.span, E0080, "constant evaluation error");
174     note_const_eval_err(tcx, err, primary_span, primary_kind, &mut diag);
175     diag
176 }
177
178 pub fn report_const_eval_err<'a, 'tcx>(
179     tcx: TyCtxt<'a, 'tcx, 'tcx>,
180     err: &ConstEvalErr,
181     primary_span: Span,
182     primary_kind: &str)
183 {
184     if let TypeckError = err.kind {
185         return;
186     }
187     build_const_eval_err(tcx, err, primary_span, primary_kind).emit();
188 }
189
190 pub fn fatal_const_eval_err<'a, 'tcx>(
191     tcx: TyCtxt<'a, 'tcx, 'tcx>,
192     err: &ConstEvalErr,
193     primary_span: Span,
194     primary_kind: &str)
195     -> !
196 {
197     report_const_eval_err(tcx, err, primary_span, primary_kind);
198     tcx.sess.abort_if_errors();
199     unreachable!()
200 }
201
202 pub fn note_const_eval_err<'a, 'tcx>(
203     _tcx: TyCtxt<'a, 'tcx, 'tcx>,
204     err: &ConstEvalErr,
205     primary_span: Span,
206     primary_kind: &str,
207     diag: &mut DiagnosticBuilder)
208 {
209     match err.description() {
210         ConstEvalErrDescription::Simple(message) => {
211             diag.span_label(err.span, &message);
212         }
213     }
214
215     if !primary_span.contains(err.span) {
216         diag.span_note(primary_span,
217                        &format!("for {} here", primary_kind));
218     }
219 }
220
221 pub struct ConstContext<'a, 'tcx: 'a> {
222     tcx: TyCtxt<'a, 'tcx, 'tcx>,
223     tables: &'a ty::TypeckTables<'tcx>,
224     substs: &'tcx Substs<'tcx>,
225     fn_args: Option<DefIdMap<ConstVal<'tcx>>>
226 }
227
228 impl<'a, 'tcx> ConstContext<'a, 'tcx> {
229     pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, body: hir::BodyId) -> Self {
230         let def_id = tcx.hir.body_owner_def_id(body);
231         ty::queries::mir_const_qualif::get(tcx, DUMMY_SP, def_id);
232         ConstContext::with_tables(tcx, tcx.item_tables(def_id))
233     }
234
235     pub fn with_tables(tcx: TyCtxt<'a, 'tcx, 'tcx>, tables: &'a ty::TypeckTables<'tcx>) -> Self {
236         ConstContext {
237             tcx: tcx,
238             tables: tables,
239             substs: tcx.intern_substs(&[]),
240             fn_args: None
241         }
242     }
243
244     /// Evaluate a constant expression in a context where the expression isn't
245     /// guaranteed to be evaluatable.
246     pub fn eval(&self, e: &Expr) -> EvalResult<'tcx> {
247         if self.tables.tainted_by_errors {
248             signal!(e, TypeckError);
249         }
250         eval_const_expr_partial(self, e)
251     }
252 }
253
254 #[derive(Clone, Debug)]
255 pub struct ConstEvalErr<'tcx> {
256     pub span: Span,
257     pub kind: ErrKind<'tcx>,
258 }
259
260 #[derive(Clone, Debug)]
261 pub enum ErrKind<'tcx> {
262     CannotCast,
263     MissingStructField,
264     NegateOn(ConstVal<'tcx>),
265     NotOn(ConstVal<'tcx>),
266     CallOn(ConstVal<'tcx>),
267
268     NonConstPath,
269     UnimplementedConstVal(&'static str),
270     ExpectedConstTuple,
271     ExpectedConstStruct,
272     IndexedNonVec,
273     IndexNotUsize,
274     IndexOutOfBounds { len: u64, index: u64 },
275
276     MiscBinaryOp,
277     MiscCatchAll,
278
279     IndexOpFeatureGated,
280     Math(ConstMathErr),
281
282     ErroneousReferencedConstant(Box<ConstEvalErr<'tcx>>),
283
284     TypeckError
285 }
286
287 impl<'tcx> From<ConstMathErr> for ErrKind<'tcx> {
288     fn from(err: ConstMathErr) -> ErrKind<'tcx> {
289         match err {
290             ConstMathErr::UnsignedNegation => TypeckError,
291             _ => Math(err)
292         }
293     }
294 }
295
296 #[derive(Clone, Debug)]
297 pub enum ConstEvalErrDescription<'a> {
298     Simple(Cow<'a, str>),
299 }
300
301 impl<'a> ConstEvalErrDescription<'a> {
302     /// Return a one-line description of the error, for lints and such
303     pub fn into_oneline(self) -> Cow<'a, str> {
304         match self {
305             ConstEvalErrDescription::Simple(simple) => simple,
306         }
307     }
308 }
309
310 impl<'tcx> ConstEvalErr<'tcx> {
311     pub fn description(&self) -> ConstEvalErrDescription {
312         use self::ErrKind::*;
313         use self::ConstEvalErrDescription::*;
314
315         macro_rules! simple {
316             ($msg:expr) => ({ Simple($msg.into_cow()) });
317             ($fmt:expr, $($arg:tt)+) => ({
318                 Simple(format!($fmt, $($arg)+).into_cow())
319             })
320         }
321
322         match self.kind {
323             CannotCast => simple!("can't cast this type"),
324             NegateOn(ref const_val) => simple!("negate on {}", const_val.description()),
325             NotOn(ref const_val) => simple!("not on {}", const_val.description()),
326             CallOn(ref const_val) => simple!("call on {}", const_val.description()),
327
328             MissingStructField  => simple!("nonexistent struct field"),
329             NonConstPath        => simple!("non-constant path in constant expression"),
330             UnimplementedConstVal(what) =>
331                 simple!("unimplemented constant expression: {}", what),
332             ExpectedConstTuple => simple!("expected constant tuple"),
333             ExpectedConstStruct => simple!("expected constant struct"),
334             IndexedNonVec => simple!("indexing is only supported for arrays"),
335             IndexNotUsize => simple!("indices must be of type `usize`"),
336             IndexOutOfBounds { len, index } => {
337                 simple!("index out of bounds: the len is {} but the index is {}",
338                         len, index)
339             }
340
341             MiscBinaryOp => simple!("bad operands for binary"),
342             MiscCatchAll => simple!("unsupported constant expr"),
343             IndexOpFeatureGated => simple!("the index operation on const values is unstable"),
344             Math(ref err) => Simple(err.description().into_cow()),
345
346             ErroneousReferencedConstant(_) => simple!("could not evaluate referenced constant"),
347
348             TypeckError => simple!("type-checking failed"),
349         }
350     }
351 }
352
353 pub type EvalResult<'tcx> = Result<ConstVal<'tcx>, ConstEvalErr<'tcx>>;
354 pub type CastResult<'tcx> = Result<ConstVal<'tcx>, ErrKind<'tcx>>;
355
356 fn eval_const_expr_partial<'a, 'tcx>(cx: &ConstContext<'a, 'tcx>,
357                                      e: &Expr) -> EvalResult<'tcx> {
358     let tcx = cx.tcx;
359     let ety = cx.tables.expr_ty(e);
360
361     // Avoid applying substitutions if they're empty, that'd ICE.
362     let ety = if cx.substs.is_empty() {
363         ety
364     } else {
365         ety.subst(tcx, cx.substs)
366     };
367
368     let result = match e.node {
369       hir::ExprUnary(hir::UnNeg, ref inner) => {
370         // unary neg literals already got their sign during creation
371         if let hir::ExprLit(ref lit) = inner.node {
372             use syntax::ast::*;
373             use syntax::ast::LitIntType::*;
374             const I8_OVERFLOW: u128 = i8::min_value() as u8 as u128;
375             const I16_OVERFLOW: u128 = i16::min_value() as u16 as u128;
376             const I32_OVERFLOW: u128 = i32::min_value() as u32 as u128;
377             const I64_OVERFLOW: u128 = i64::min_value() as u64 as u128;
378             const I128_OVERFLOW: u128 = i128::min_value() as u128;
379             match (&lit.node, &ety.sty) {
380                 (&LitKind::Int(I8_OVERFLOW, _), &ty::TyInt(IntTy::I8)) |
381                 (&LitKind::Int(I8_OVERFLOW, Signed(IntTy::I8)), _) => {
382                     return Ok(Integral(I8(i8::min_value())))
383                 },
384                 (&LitKind::Int(I16_OVERFLOW, _), &ty::TyInt(IntTy::I16)) |
385                 (&LitKind::Int(I16_OVERFLOW, Signed(IntTy::I16)), _) => {
386                     return Ok(Integral(I16(i16::min_value())))
387                 },
388                 (&LitKind::Int(I32_OVERFLOW, _), &ty::TyInt(IntTy::I32)) |
389                 (&LitKind::Int(I32_OVERFLOW, Signed(IntTy::I32)), _) => {
390                     return Ok(Integral(I32(i32::min_value())))
391                 },
392                 (&LitKind::Int(I64_OVERFLOW, _), &ty::TyInt(IntTy::I64)) |
393                 (&LitKind::Int(I64_OVERFLOW, Signed(IntTy::I64)), _) => {
394                     return Ok(Integral(I64(i64::min_value())))
395                 },
396                 (&LitKind::Int(I128_OVERFLOW, _), &ty::TyInt(IntTy::I128)) |
397                 (&LitKind::Int(I128_OVERFLOW, Signed(IntTy::I128)), _) => {
398                     return Ok(Integral(I128(i128::min_value())))
399                 },
400                 (&LitKind::Int(n, _), &ty::TyInt(IntTy::Is)) |
401                 (&LitKind::Int(n, Signed(IntTy::Is)), _) => {
402                     match tcx.sess.target.int_type {
403                         IntTy::I16 => if n == I16_OVERFLOW {
404                             return Ok(Integral(Isize(Is16(i16::min_value()))));
405                         },
406                         IntTy::I32 => if n == I32_OVERFLOW {
407                             return Ok(Integral(Isize(Is32(i32::min_value()))));
408                         },
409                         IntTy::I64 => if n == I64_OVERFLOW {
410                             return Ok(Integral(Isize(Is64(i64::min_value()))));
411                         },
412                         _ => span_bug!(e.span, "typeck error")
413                     }
414                 },
415                 _ => {},
416             }
417         }
418         match cx.eval(inner)? {
419           Float(f) => Float(-f),
420           Integral(i) => Integral(math!(e, -i)),
421           const_val => signal!(e, NegateOn(const_val)),
422         }
423       }
424       hir::ExprUnary(hir::UnNot, ref inner) => {
425         match cx.eval(inner)? {
426           Integral(i) => Integral(math!(e, !i)),
427           Bool(b) => Bool(!b),
428           const_val => signal!(e, NotOn(const_val)),
429         }
430       }
431       hir::ExprUnary(hir::UnDeref, _) => signal!(e, UnimplementedConstVal("deref operation")),
432       hir::ExprBinary(op, ref a, ref b) => {
433         // technically, if we don't have type hints, but integral eval
434         // gives us a type through a type-suffix, cast or const def type
435         // we need to re-eval the other value of the BinOp if it was
436         // not inferred
437         match (cx.eval(a)?, cx.eval(b)?) {
438           (Float(a), Float(b)) => {
439             use std::cmp::Ordering::*;
440             match op.node {
441               hir::BiAdd => Float(math!(e, a + b)),
442               hir::BiSub => Float(math!(e, a - b)),
443               hir::BiMul => Float(math!(e, a * b)),
444               hir::BiDiv => Float(math!(e, a / b)),
445               hir::BiRem => Float(math!(e, a % b)),
446               hir::BiEq => Bool(math!(e, a.try_cmp(b)) == Equal),
447               hir::BiLt => Bool(math!(e, a.try_cmp(b)) == Less),
448               hir::BiLe => Bool(math!(e, a.try_cmp(b)) != Greater),
449               hir::BiNe => Bool(math!(e, a.try_cmp(b)) != Equal),
450               hir::BiGe => Bool(math!(e, a.try_cmp(b)) != Less),
451               hir::BiGt => Bool(math!(e, a.try_cmp(b)) == Greater),
452               _ => span_bug!(e.span, "typeck error"),
453             }
454           }
455           (Integral(a), Integral(b)) => {
456             use std::cmp::Ordering::*;
457             match op.node {
458               hir::BiAdd => Integral(math!(e, a + b)),
459               hir::BiSub => Integral(math!(e, a - b)),
460               hir::BiMul => Integral(math!(e, a * b)),
461               hir::BiDiv => Integral(math!(e, a / b)),
462               hir::BiRem => Integral(math!(e, a % b)),
463               hir::BiBitAnd => Integral(math!(e, a & b)),
464               hir::BiBitOr => Integral(math!(e, a | b)),
465               hir::BiBitXor => Integral(math!(e, a ^ b)),
466               hir::BiShl => Integral(math!(e, a << b)),
467               hir::BiShr => Integral(math!(e, a >> b)),
468               hir::BiEq => Bool(math!(e, a.try_cmp(b)) == Equal),
469               hir::BiLt => Bool(math!(e, a.try_cmp(b)) == Less),
470               hir::BiLe => Bool(math!(e, a.try_cmp(b)) != Greater),
471               hir::BiNe => Bool(math!(e, a.try_cmp(b)) != Equal),
472               hir::BiGe => Bool(math!(e, a.try_cmp(b)) != Less),
473               hir::BiGt => Bool(math!(e, a.try_cmp(b)) == Greater),
474               _ => span_bug!(e.span, "typeck error"),
475             }
476           }
477           (Bool(a), Bool(b)) => {
478             Bool(match op.node {
479               hir::BiAnd => a && b,
480               hir::BiOr => a || b,
481               hir::BiBitXor => a ^ b,
482               hir::BiBitAnd => a & b,
483               hir::BiBitOr => a | b,
484               hir::BiEq => a == b,
485               hir::BiNe => a != b,
486               hir::BiLt => a < b,
487               hir::BiLe => a <= b,
488               hir::BiGe => a >= b,
489               hir::BiGt => a > b,
490               _ => span_bug!(e.span, "typeck error"),
491              })
492           }
493
494           _ => signal!(e, MiscBinaryOp),
495         }
496       }
497       hir::ExprCast(ref base, _) => {
498         match cast_const(tcx, cx.eval(base)?, ety) {
499             Ok(val) => val,
500             Err(kind) => return Err(ConstEvalErr { span: e.span, kind: kind }),
501         }
502       }
503       hir::ExprPath(ref qpath) => {
504         let substs = cx.tables.node_id_item_substs(e.id)
505             .unwrap_or_else(|| tcx.intern_substs(&[]));
506
507         // Avoid applying substitutions if they're empty, that'd ICE.
508         let substs = if cx.substs.is_empty() {
509             substs
510         } else {
511             substs.subst(tcx, cx.substs)
512         };
513
514           match cx.tables.qpath_def(qpath, e.id) {
515               Def::Const(def_id) |
516               Def::AssociatedConst(def_id) => {
517                   if let Some((expr, tables)) = lookup_const_by_id(tcx, def_id, substs) {
518                       let cx = ConstContext::with_tables(tcx, tables);
519                       match cx.eval(expr) {
520                           Ok(val) => val,
521                           Err(ConstEvalErr { kind: TypeckError, .. }) => {
522                               signal!(e, TypeckError);
523                           }
524                           Err(err) => {
525                               debug!("bad reference: {:?}, {:?}", err.description(), err.span);
526                               signal!(e, ErroneousReferencedConstant(box err))
527                           },
528                       }
529                   } else {
530                       signal!(e, TypeckError);
531                   }
532               },
533               Def::VariantCtor(variant_def, ..) => {
534                   if let Some((expr, tables)) = lookup_variant_by_id(tcx, variant_def) {
535                       let cx = ConstContext::with_tables(tcx, tables);
536                       match cx.eval(expr) {
537                           Ok(val) => val,
538                           Err(ConstEvalErr { kind: TypeckError, .. }) => {
539                               signal!(e, TypeckError);
540                           }
541                           Err(err) => {
542                               debug!("bad reference: {:?}, {:?}", err.description(), err.span);
543                               signal!(e, ErroneousReferencedConstant(box err))
544                           },
545                       }
546                   } else {
547                       signal!(e, UnimplementedConstVal("enum variants"));
548                   }
549               }
550               Def::StructCtor(..) => {
551                   ConstVal::Struct(Default::default())
552               }
553               Def::Local(def_id) => {
554                   debug!("Def::Local({:?}): {:?}", def_id, cx.fn_args);
555                   if let Some(val) = cx.fn_args.as_ref().and_then(|args| args.get(&def_id)) {
556                       val.clone()
557                   } else {
558                       signal!(e, NonConstPath);
559                   }
560               },
561               Def::Method(id) | Def::Fn(id) => Function(id, substs),
562               Def::Err => span_bug!(e.span, "typeck error"),
563               _ => signal!(e, NonConstPath),
564           }
565       }
566       hir::ExprCall(ref callee, ref args) => {
567           let (did, substs) = match cx.eval(callee)? {
568               Function(did, substs) => (did, substs),
569               Struct(_) => signal!(e, UnimplementedConstVal("tuple struct constructors")),
570               callee => signal!(e, CallOn(callee)),
571           };
572           let (body, tables) = match lookup_const_fn_by_id(tcx, did) {
573               Some(x) => x,
574               None => signal!(e, NonConstPath),
575           };
576
577           let arg_defs = body.arguments.iter().map(|arg| match arg.pat.node {
578                hir::PatKind::Binding(_, def_id, _, _) => Some(def_id),
579                _ => None
580            }).collect::<Vec<_>>();
581           assert_eq!(arg_defs.len(), args.len());
582
583           let mut call_args = DefIdMap();
584           for (arg, arg_expr) in arg_defs.into_iter().zip(args.iter()) {
585               let arg_val = cx.eval(arg_expr)?;
586               debug!("const call arg: {:?}", arg);
587               if let Some(def_id) = arg {
588                 assert!(call_args.insert(def_id, arg_val).is_none());
589               }
590           }
591           debug!("const call({:?})", call_args);
592           let callee_cx = ConstContext {
593             tcx: tcx,
594             tables: tables,
595             substs: substs,
596             fn_args: Some(call_args)
597           };
598           callee_cx.eval(&body.value)?
599       },
600       hir::ExprLit(ref lit) => match lit_to_const(&lit.node, tcx, ety) {
601           Ok(val) => val,
602           Err(err) => signal!(e, err),
603       },
604       hir::ExprBlock(ref block) => {
605         match block.expr {
606             Some(ref expr) => cx.eval(expr)?,
607             None => Tuple(vec![]),
608         }
609       }
610       hir::ExprType(ref e, _) => cx.eval(e)?,
611       hir::ExprTup(ref fields) => {
612         Tuple(fields.iter().map(|e| cx.eval(e)).collect::<Result<_, _>>()?)
613       }
614       hir::ExprStruct(_, ref fields, _) => {
615         Struct(fields.iter().map(|f| {
616             cx.eval(&f.expr).map(|v| (f.name.node, v))
617         }).collect::<Result<_, _>>()?)
618       }
619       hir::ExprIndex(ref arr, ref idx) => {
620         if !tcx.sess.features.borrow().const_indexing {
621             signal!(e, IndexOpFeatureGated);
622         }
623         let arr = cx.eval(arr)?;
624         let idx = match cx.eval(idx)? {
625             Integral(Usize(i)) => i.as_u64(tcx.sess.target.uint_type),
626             _ => signal!(idx, IndexNotUsize),
627         };
628         assert_eq!(idx as usize as u64, idx);
629         match arr {
630             Array(ref v) => {
631                 if let Some(elem) = v.get(idx as usize) {
632                     elem.clone()
633                 } else {
634                     let n = v.len() as u64;
635                     assert_eq!(n as usize as u64, n);
636                     signal!(e, IndexOutOfBounds { len: n, index: idx })
637                 }
638             }
639
640             Repeat(.., n) if idx >= n => {
641                 signal!(e, IndexOutOfBounds { len: n, index: idx })
642             }
643             Repeat(ref elem, _) => (**elem).clone(),
644
645             ByteStr(ref data) if idx >= data.len() as u64 => {
646                 signal!(e, IndexOutOfBounds { len: data.len() as u64, index: idx })
647             }
648             ByteStr(data) => {
649                 Integral(U8(data[idx as usize]))
650             },
651
652             _ => signal!(e, IndexedNonVec),
653         }
654       }
655       hir::ExprArray(ref v) => {
656         Array(v.iter().map(|e| cx.eval(e)).collect::<Result<_, _>>()?)
657       }
658       hir::ExprRepeat(ref elem, _) => {
659           let n = match ety.sty {
660             ty::TyArray(_, n) => n as u64,
661             _ => span_bug!(e.span, "typeck error")
662           };
663           Repeat(Box::new(cx.eval(elem)?), n)
664       },
665       hir::ExprTupField(ref base, index) => {
666         let c = cx.eval(base)?;
667         if let Tuple(ref fields) = c {
668             fields[index.node].clone()
669         } else {
670             signal!(base, ExpectedConstTuple);
671         }
672       }
673       hir::ExprField(ref base, field_name) => {
674         let c = cx.eval(base)?;
675         if let Struct(ref fields) = c {
676             if let Some(f) = fields.get(&field_name.node) {
677                 f.clone()
678             } else {
679                 signal!(e, MissingStructField);
680             }
681         } else {
682             signal!(base, ExpectedConstStruct);
683         }
684       }
685       hir::ExprAddrOf(..) => signal!(e, UnimplementedConstVal("address operator")),
686       _ => signal!(e, MiscCatchAll)
687     };
688
689     Ok(result)
690 }
691
692 fn resolve_trait_associated_const<'a, 'tcx: 'a>(
693     tcx: TyCtxt<'a, 'tcx, 'tcx>,
694     trait_item_id: DefId,
695     default_value: Option<(&'tcx Expr, &'a ty::TypeckTables<'tcx>)>,
696     trait_id: DefId,
697     rcvr_substs: &'tcx Substs<'tcx>
698 ) -> Option<(&'tcx Expr, &'a ty::TypeckTables<'tcx>)>
699 {
700     let trait_ref = ty::Binder(ty::TraitRef::new(trait_id, rcvr_substs));
701     debug!("resolve_trait_associated_const: trait_ref={:?}",
702            trait_ref);
703
704     tcx.populate_implementations_for_trait_if_necessary(trait_id);
705     tcx.infer_ctxt((), Reveal::UserFacing).enter(|infcx| {
706         let mut selcx = traits::SelectionContext::new(&infcx);
707         let obligation = traits::Obligation::new(traits::ObligationCause::dummy(),
708                                                  trait_ref.to_poly_trait_predicate());
709         let selection = match selcx.select(&obligation) {
710             Ok(Some(vtable)) => vtable,
711             // Still ambiguous, so give up and let the caller decide whether this
712             // expression is really needed yet. Some associated constant values
713             // can't be evaluated until monomorphization is done in trans.
714             Ok(None) => {
715                 return None
716             }
717             Err(_) => {
718                 return None
719             }
720         };
721
722         // NOTE: this code does not currently account for specialization, but when
723         // it does so, it should hook into the Reveal to determine when the
724         // constant should resolve; this will also require plumbing through to this
725         // function whether we are in "trans mode" to pick the right Reveal
726         // when constructing the inference context above.
727         match selection {
728             traits::VtableImpl(ref impl_data) => {
729                 let name = tcx.associated_item(trait_item_id).name;
730                 let ac = tcx.associated_items(impl_data.impl_def_id)
731                     .find(|item| item.kind == ty::AssociatedKind::Const && item.name == name);
732                 match ac {
733                     Some(ic) => lookup_const_by_id(tcx, ic.def_id, Substs::empty()),
734                     None => default_value,
735                 }
736             }
737             _ => {
738                 bug!("resolve_trait_associated_const: unexpected vtable type")
739             }
740         }
741     })
742 }
743
744 fn cast_const_int<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
745                             val: ConstInt,
746                             ty: Ty<'tcx>)
747                             -> CastResult<'tcx> {
748     let v = val.to_u128_unchecked();
749     match ty.sty {
750         ty::TyBool if v == 0 => Ok(Bool(false)),
751         ty::TyBool if v == 1 => Ok(Bool(true)),
752         ty::TyInt(ast::IntTy::I8) => Ok(Integral(I8(v as i128 as i8))),
753         ty::TyInt(ast::IntTy::I16) => Ok(Integral(I16(v as i128 as i16))),
754         ty::TyInt(ast::IntTy::I32) => Ok(Integral(I32(v as i128 as i32))),
755         ty::TyInt(ast::IntTy::I64) => Ok(Integral(I64(v as i128 as i64))),
756         ty::TyInt(ast::IntTy::I128) => Ok(Integral(I128(v as i128))),
757         ty::TyInt(ast::IntTy::Is) => {
758             Ok(Integral(Isize(ConstIsize::new_truncating(v as i128, tcx.sess.target.int_type))))
759         },
760         ty::TyUint(ast::UintTy::U8) => Ok(Integral(U8(v as u8))),
761         ty::TyUint(ast::UintTy::U16) => Ok(Integral(U16(v as u16))),
762         ty::TyUint(ast::UintTy::U32) => Ok(Integral(U32(v as u32))),
763         ty::TyUint(ast::UintTy::U64) => Ok(Integral(U64(v as u64))),
764         ty::TyUint(ast::UintTy::U128) => Ok(Integral(U128(v as u128))),
765         ty::TyUint(ast::UintTy::Us) => {
766             Ok(Integral(Usize(ConstUsize::new_truncating(v, tcx.sess.target.uint_type))))
767         },
768         ty::TyFloat(ast::FloatTy::F64) => Ok(Float(F64(val.to_f64()))),
769         ty::TyFloat(ast::FloatTy::F32) => Ok(Float(F32(val.to_f32()))),
770         ty::TyRawPtr(_) => Err(ErrKind::UnimplementedConstVal("casting an address to a raw ptr")),
771         ty::TyChar => match val {
772             U8(u) => Ok(Char(u as char)),
773             _ => bug!(),
774         },
775         _ => bug!(),
776     }
777 }
778
779 fn cast_const_float<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
780                               val: ConstFloat,
781                               ty: Ty<'tcx>) -> CastResult<'tcx> {
782     match ty.sty {
783         ty::TyInt(_) | ty::TyUint(_) => {
784             let i = match val {
785                 F32(f) if f >= 0.0 => U128(f as u128),
786                 F64(f) if f >= 0.0 => U128(f as u128),
787
788                 F32(f) => I128(f as i128),
789                 F64(f) => I128(f as i128)
790             };
791
792             if let (I128(_), &ty::TyUint(_)) = (i, &ty.sty) {
793                 return Err(CannotCast);
794             }
795
796             cast_const_int(tcx, i, ty)
797         }
798         ty::TyFloat(ast::FloatTy::F64) => Ok(Float(F64(match val {
799             F32(f) => f as f64,
800             F64(f) => f
801         }))),
802         ty::TyFloat(ast::FloatTy::F32) => Ok(Float(F32(match val {
803             F64(f) => f as f32,
804             F32(f) => f
805         }))),
806         _ => Err(CannotCast),
807     }
808 }
809
810 fn cast_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
811                         val: ConstVal<'tcx>,
812                         ty: Ty<'tcx>)
813                         -> CastResult<'tcx> {
814     match val {
815         Integral(i) => cast_const_int(tcx, i, ty),
816         Bool(b) => cast_const_int(tcx, U8(b as u8), ty),
817         Float(f) => cast_const_float(tcx, f, ty),
818         Char(c) => cast_const_int(tcx, U32(c as u32), ty),
819         Function(..) => Err(UnimplementedConstVal("casting fn pointers")),
820         ByteStr(b) => match ty.sty {
821             ty::TyRawPtr(_) => {
822                 Err(ErrKind::UnimplementedConstVal("casting a bytestr to a raw ptr"))
823             },
824             ty::TyRef(_, ty::TypeAndMut { ref ty, mutbl: hir::MutImmutable }) => match ty.sty {
825                 ty::TyArray(ty, n) if ty == tcx.types.u8 && n == b.len() => Ok(ByteStr(b)),
826                 ty::TySlice(_) => {
827                     Err(ErrKind::UnimplementedConstVal("casting a bytestr to slice"))
828                 },
829                 _ => Err(CannotCast),
830             },
831             _ => Err(CannotCast),
832         },
833         Str(s) => match ty.sty {
834             ty::TyRawPtr(_) => Err(ErrKind::UnimplementedConstVal("casting a str to a raw ptr")),
835             ty::TyRef(_, ty::TypeAndMut { ref ty, mutbl: hir::MutImmutable }) => match ty.sty {
836                 ty::TyStr => Ok(Str(s)),
837                 _ => Err(CannotCast),
838             },
839             _ => Err(CannotCast),
840         },
841         _ => Err(CannotCast),
842     }
843 }
844
845 fn lit_to_const<'a, 'tcx>(lit: &ast::LitKind,
846                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
847                           mut ty: Ty<'tcx>)
848                           -> Result<ConstVal<'tcx>, ErrKind<'tcx>> {
849     use syntax::ast::*;
850     use syntax::ast::LitIntType::*;
851
852     if let ty::TyAdt(adt, _) = ty.sty {
853         if adt.is_enum() {
854             ty = adt.repr.discr_type().to_ty(tcx)
855         }
856     }
857
858     match *lit {
859         LitKind::Str(ref s, _) => Ok(Str(s.as_str())),
860         LitKind::ByteStr(ref data) => Ok(ByteStr(data.clone())),
861         LitKind::Byte(n) => Ok(Integral(U8(n))),
862         LitKind::Int(n, hint) => {
863             match (&ty.sty, hint) {
864                 (&ty::TyInt(ity), _) |
865                 (_, Signed(ity)) => {
866                     Ok(Integral(ConstInt::new_signed_truncating(n as i128,
867                         ity, tcx.sess.target.int_type)))
868                 }
869                 (&ty::TyUint(uty), _) |
870                 (_, Unsigned(uty)) => {
871                     Ok(Integral(ConstInt::new_unsigned_truncating(n as u128,
872                         uty, tcx.sess.target.uint_type)))
873                 }
874                 _ => bug!()
875             }
876         }
877         LitKind::Float(n, fty) => {
878             parse_float(&n.as_str(), fty).map(Float)
879         }
880         LitKind::FloatUnsuffixed(n) => {
881             let fty = match ty.sty {
882                 ty::TyFloat(fty) => fty,
883                 _ => bug!()
884             };
885             parse_float(&n.as_str(), fty).map(Float)
886         }
887         LitKind::Bool(b) => Ok(Bool(b)),
888         LitKind::Char(c) => Ok(Char(c)),
889     }
890 }
891
892 fn parse_float<'tcx>(num: &str, fty: ast::FloatTy)
893                      -> Result<ConstFloat, ErrKind<'tcx>> {
894     let val = match fty {
895         ast::FloatTy::F32 => num.parse::<f32>().map(F32),
896         ast::FloatTy::F64 => num.parse::<f64>().map(F64)
897     };
898     val.map_err(|_| {
899         // FIXME(#31407) this is only necessary because float parsing is buggy
900         UnimplementedConstVal("could not evaluate float literal (see issue #31407)")
901     })
902 }
903
904 pub fn compare_const_vals(tcx: TyCtxt, span: Span, a: &ConstVal, b: &ConstVal)
905                           -> Result<Ordering, ErrorReported>
906 {
907     let result = match (a, b) {
908         (&Integral(a), &Integral(b)) => a.try_cmp(b).ok(),
909         (&Float(a), &Float(b)) => a.try_cmp(b).ok(),
910         (&Str(ref a), &Str(ref b)) => Some(a.cmp(b)),
911         (&Bool(a), &Bool(b)) => Some(a.cmp(&b)),
912         (&ByteStr(ref a), &ByteStr(ref b)) => Some(a.cmp(b)),
913         (&Char(a), &Char(ref b)) => Some(a.cmp(b)),
914         _ => None,
915     };
916
917     match result {
918         Some(result) => Ok(result),
919         None => {
920             // FIXME: can this ever be reached?
921             span_err!(tcx.sess, span, E0298,
922                       "type mismatch comparing {} and {}",
923                       a.description(),
924                       b.description());
925             Err(ErrorReported)
926         }
927     }
928 }
929
930 impl<'a, 'tcx> ConstContext<'a, 'tcx> {
931     pub fn compare_lit_exprs(&self,
932                              span: Span,
933                              a: &Expr,
934                              b: &Expr) -> Result<Ordering, ErrorReported> {
935         let tcx = self.tcx;
936         let a = match self.eval(a) {
937             Ok(a) => a,
938             Err(e) => {
939                 report_const_eval_err(tcx, &e, a.span, "expression");
940                 return Err(ErrorReported);
941             }
942         };
943         let b = match self.eval(b) {
944             Ok(b) => b,
945             Err(e) => {
946                 report_const_eval_err(tcx, &e, b.span, "expression");
947                 return Err(ErrorReported);
948             }
949         };
950         compare_const_vals(tcx, span, &a, &b)
951     }
952 }
953
954
955 /// Returns the value of the length-valued expression
956 pub fn eval_length<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
957                              count: hir::BodyId,
958                              reason: &str)
959                              -> Result<usize, ErrorReported>
960 {
961     let count_expr = &tcx.hir.body(count).value;
962     match ConstContext::new(tcx, count).eval(count_expr) {
963         Ok(Integral(Usize(count))) => {
964             let val = count.as_u64(tcx.sess.target.uint_type);
965             assert_eq!(val as usize as u64, val);
966             Ok(val as usize)
967         },
968         Ok(_) |
969         Err(ConstEvalErr { kind: TypeckError, .. }) => Err(ErrorReported),
970         Err(err) => {
971             let mut diag = build_const_eval_err(
972                 tcx, &err, count_expr.span, reason);
973
974             if let hir::ExprPath(hir::QPath::Resolved(None, ref path)) = count_expr.node {
975                 if let Def::Local(..) = path.def {
976                     diag.note(&format!("`{}` is a variable",
977                                        tcx.hir.node_to_pretty_string(count_expr.id)));
978                 }
979             }
980
981             diag.emit();
982             Err(ErrorReported)
983         }
984     }
985 }