]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/const_eval.rs
Auto merge of #56770 - satyarohith:patch-1, r=Centril
[rust.git] / src / librustc_mir / const_eval.rs
1 // Copyright 2018 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 // Not in interpret to make sure we do not use private implementation details
12
13 use std::fmt;
14 use std::error::Error;
15 use std::borrow::{Borrow, Cow};
16 use std::hash::Hash;
17 use std::collections::hash_map::Entry;
18
19 use rustc::hir::{self, def_id::DefId};
20 use rustc::hir::def::Def;
21 use rustc::mir::interpret::{ConstEvalErr, ErrorHandled};
22 use rustc::mir;
23 use rustc::ty::{self, TyCtxt, Instance, query::TyCtxtAt};
24 use rustc::ty::layout::{self, LayoutOf, TyLayout, VariantIdx};
25 use rustc::ty::subst::Subst;
26 use rustc::traits::Reveal;
27 use rustc_data_structures::indexed_vec::IndexVec;
28 use rustc_data_structures::fx::FxHashMap;
29 use rustc::util::common::ErrorReported;
30
31 use syntax::ast::Mutability;
32 use syntax::source_map::{Span, DUMMY_SP};
33
34 use crate::interpret::{self,
35     PlaceTy, MPlaceTy, MemPlace, OpTy, Operand, Immediate, Scalar, RawConst, ConstValue, Pointer,
36     EvalResult, EvalError, EvalErrorKind, GlobalId, EvalContext, StackPopCleanup,
37     Allocation, AllocId, MemoryKind,
38     snapshot, RefTracking,
39 };
40
41 /// Number of steps until the detector even starts doing anything.
42 /// Also, a warning is shown to the user when this number is reached.
43 const STEPS_UNTIL_DETECTOR_ENABLED: isize = 1_000_000;
44 /// The number of steps between loop detector snapshots.
45 /// Should be a power of two for performance reasons.
46 const DETECTOR_SNAPSHOT_PERIOD: isize = 256;
47
48 pub fn mk_borrowck_eval_cx<'a, 'mir, 'tcx>(
49     tcx: TyCtxt<'a, 'tcx, 'tcx>,
50     instance: Instance<'tcx>,
51     mir: &'mir mir::Mir<'tcx>,
52     span: Span,
53 ) -> EvalResult<'tcx, CompileTimeEvalContext<'a, 'mir, 'tcx>> {
54     debug!("mk_borrowck_eval_cx: {:?}", instance);
55     let param_env = tcx.param_env(instance.def_id());
56     let mut ecx = EvalContext::new(tcx.at(span), param_env, CompileTimeInterpreter::new());
57     // insert a stack frame so any queries have the correct substs
58     // cannot use `push_stack_frame`; if we do `const_prop` explodes
59     ecx.stack.push(interpret::Frame {
60         block: mir::START_BLOCK,
61         locals: IndexVec::new(),
62         instance,
63         span,
64         mir,
65         return_place: None,
66         return_to_block: StackPopCleanup::Goto(None), // never pop
67         stmt: 0,
68         extra: (),
69     });
70     Ok(ecx)
71 }
72
73 pub fn mk_eval_cx<'a, 'tcx>(
74     tcx: TyCtxt<'a, 'tcx, 'tcx>,
75     instance: Instance<'tcx>,
76     param_env: ty::ParamEnv<'tcx>,
77 ) -> EvalResult<'tcx, CompileTimeEvalContext<'a, 'tcx, 'tcx>> {
78     debug!("mk_eval_cx: {:?}, {:?}", instance, param_env);
79     let span = tcx.def_span(instance.def_id());
80     let mut ecx = EvalContext::new(tcx.at(span), param_env, CompileTimeInterpreter::new());
81     let mir = ecx.load_mir(instance.def)?;
82     // insert a stack frame so any queries have the correct substs
83     ecx.push_stack_frame(
84         instance,
85         mir.span,
86         mir,
87         None,
88         StackPopCleanup::Goto(None), // never pop
89     )?;
90     Ok(ecx)
91 }
92
93 pub(crate) fn eval_promoted<'a, 'mir, 'tcx>(
94     tcx: TyCtxt<'a, 'tcx, 'tcx>,
95     cid: GlobalId<'tcx>,
96     mir: &'mir mir::Mir<'tcx>,
97     param_env: ty::ParamEnv<'tcx>,
98 ) -> EvalResult<'tcx, MPlaceTy<'tcx>> {
99     let mut ecx = mk_borrowck_eval_cx(tcx, cid.instance, mir, DUMMY_SP).unwrap();
100     eval_body_using_ecx(&mut ecx, cid, Some(mir), param_env)
101 }
102
103 // FIXME: These two conversion functions are bad hacks.  We should just always use allocations.
104 pub fn op_to_const<'tcx>(
105     ecx: &CompileTimeEvalContext<'_, '_, 'tcx>,
106     op: OpTy<'tcx>,
107     may_normalize: bool,
108 ) -> EvalResult<'tcx, &'tcx ty::Const<'tcx>> {
109     // We do not normalize just any data.  Only scalar layout and fat pointers.
110     let normalize = may_normalize
111         && match op.layout.abi {
112             layout::Abi::Scalar(..) => true,
113             layout::Abi::ScalarPair(..) => {
114                 // Must be a fat pointer
115                 op.layout.ty.builtin_deref(true).is_some()
116             },
117             _ => false,
118         };
119     let normalized_op = if normalize {
120         ecx.try_read_immediate(op)?
121     } else {
122         match op.op {
123             Operand::Indirect(mplace) => Err(mplace),
124             Operand::Immediate(val) => Ok(val)
125         }
126     };
127     let val = match normalized_op {
128         Err(MemPlace { ptr, align, meta }) => {
129             // extract alloc-offset pair
130             assert!(meta.is_none());
131             let ptr = ptr.to_ptr()?;
132             let alloc = ecx.memory.get(ptr.alloc_id)?;
133             assert!(alloc.align >= align);
134             assert!(alloc.bytes.len() as u64 - ptr.offset.bytes() >= op.layout.size.bytes());
135             let mut alloc = alloc.clone();
136             alloc.align = align;
137             // FIXME shouldn't it be the case that `mark_static_initialized` has already
138             // interned this?  I thought that is the entire point of that `FinishStatic` stuff?
139             let alloc = ecx.tcx.intern_const_alloc(alloc);
140             ConstValue::ByRef(ptr.alloc_id, alloc, ptr.offset)
141         },
142         Ok(Immediate::Scalar(x)) =>
143             ConstValue::Scalar(x.not_undef()?),
144         Ok(Immediate::ScalarPair(a, b)) =>
145             ConstValue::ScalarPair(a.not_undef()?, b.not_undef()?),
146     };
147     Ok(ty::Const::from_const_value(ecx.tcx.tcx, val, op.layout.ty))
148 }
149 pub fn const_to_op<'tcx>(
150     ecx: &CompileTimeEvalContext<'_, '_, 'tcx>,
151     cnst: &ty::Const<'tcx>,
152 ) -> EvalResult<'tcx, OpTy<'tcx>> {
153     let op = ecx.const_value_to_op(cnst.val)?;
154     Ok(OpTy { op, layout: ecx.layout_of(cnst.ty)? })
155 }
156
157 fn eval_body_and_ecx<'a, 'mir, 'tcx>(
158     tcx: TyCtxt<'a, 'tcx, 'tcx>,
159     cid: GlobalId<'tcx>,
160     mir: Option<&'mir mir::Mir<'tcx>>,
161     param_env: ty::ParamEnv<'tcx>,
162 ) -> (EvalResult<'tcx, MPlaceTy<'tcx>>, CompileTimeEvalContext<'a, 'mir, 'tcx>) {
163     // we start out with the best span we have
164     // and try improving it down the road when more information is available
165     let span = tcx.def_span(cid.instance.def_id());
166     let span = mir.map(|mir| mir.span).unwrap_or(span);
167     let mut ecx = EvalContext::new(tcx.at(span), param_env, CompileTimeInterpreter::new());
168     let r = eval_body_using_ecx(&mut ecx, cid, mir, param_env);
169     (r, ecx)
170 }
171
172 // Returns a pointer to where the result lives
173 fn eval_body_using_ecx<'mir, 'tcx>(
174     ecx: &mut CompileTimeEvalContext<'_, 'mir, 'tcx>,
175     cid: GlobalId<'tcx>,
176     mir: Option<&'mir mir::Mir<'tcx>>,
177     param_env: ty::ParamEnv<'tcx>,
178 ) -> EvalResult<'tcx, MPlaceTy<'tcx>> {
179     debug!("eval_body_using_ecx: {:?}, {:?}", cid, param_env);
180     let tcx = ecx.tcx.tcx;
181     let mut mir = match mir {
182         Some(mir) => mir,
183         None => ecx.load_mir(cid.instance.def)?,
184     };
185     if let Some(index) = cid.promoted {
186         mir = &mir.promoted[index];
187     }
188     let layout = ecx.layout_of(mir.return_ty().subst(tcx, cid.instance.substs))?;
189     assert!(!layout.is_unsized());
190     let ret = ecx.allocate(layout, MemoryKind::Stack);
191
192     let name = ty::tls::with(|tcx| tcx.item_path_str(cid.instance.def_id()));
193     let prom = cid.promoted.map_or(String::new(), |p| format!("::promoted[{:?}]", p));
194     trace!("eval_body_using_ecx: pushing stack frame for global: {}{}", name, prom);
195     assert!(mir.arg_count == 0);
196     ecx.push_stack_frame(
197         cid.instance,
198         mir.span,
199         mir,
200         Some(ret.into()),
201         StackPopCleanup::None { cleanup: false },
202     )?;
203
204     // The main interpreter loop.
205     ecx.run()?;
206
207     // Intern the result
208     let internally_mutable = !layout.ty.is_freeze(tcx, param_env, mir.span);
209     let is_static = tcx.is_static(cid.instance.def_id());
210     let mutability = if is_static == Some(hir::Mutability::MutMutable) || internally_mutable {
211         Mutability::Mutable
212     } else {
213         Mutability::Immutable
214     };
215     ecx.memory.intern_static(ret.ptr.to_ptr()?.alloc_id, mutability)?;
216
217     debug!("eval_body_using_ecx done: {:?}", *ret);
218     Ok(ret)
219 }
220
221 impl<'tcx> Into<EvalError<'tcx>> for ConstEvalError {
222     fn into(self) -> EvalError<'tcx> {
223         EvalErrorKind::MachineError(self.to_string()).into()
224     }
225 }
226
227 #[derive(Clone, Debug)]
228 enum ConstEvalError {
229     NeedsRfc(String),
230 }
231
232 impl fmt::Display for ConstEvalError {
233     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
234         use self::ConstEvalError::*;
235         match *self {
236             NeedsRfc(ref msg) => {
237                 write!(
238                     f,
239                     "\"{}\" needs an rfc before being allowed inside constants",
240                     msg
241                 )
242             }
243         }
244     }
245 }
246
247 impl Error for ConstEvalError {
248     fn description(&self) -> &str {
249         use self::ConstEvalError::*;
250         match *self {
251             NeedsRfc(_) => "this feature needs an rfc before being allowed inside constants",
252         }
253     }
254
255     fn cause(&self) -> Option<&dyn Error> {
256         None
257     }
258 }
259
260 // Extra machine state for CTFE, and the Machine instance
261 pub struct CompileTimeInterpreter<'a, 'mir, 'tcx: 'a+'mir> {
262     /// When this value is negative, it indicates the number of interpreter
263     /// steps *until* the loop detector is enabled. When it is positive, it is
264     /// the number of steps after the detector has been enabled modulo the loop
265     /// detector period.
266     pub(super) steps_since_detector_enabled: isize,
267
268     /// Extra state to detect loops.
269     pub(super) loop_detector: snapshot::InfiniteLoopDetector<'a, 'mir, 'tcx>,
270 }
271
272 impl<'a, 'mir, 'tcx> CompileTimeInterpreter<'a, 'mir, 'tcx> {
273     fn new() -> Self {
274         CompileTimeInterpreter {
275             loop_detector: Default::default(),
276             steps_since_detector_enabled: -STEPS_UNTIL_DETECTOR_ENABLED,
277         }
278     }
279 }
280
281 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
282     #[inline(always)]
283     fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
284         where K: Borrow<Q>
285     {
286         FxHashMap::contains_key(self, k)
287     }
288
289     #[inline(always)]
290     fn insert(&mut self, k: K, v: V) -> Option<V>
291     {
292         FxHashMap::insert(self, k, v)
293     }
294
295     #[inline(always)]
296     fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
297         where K: Borrow<Q>
298     {
299         FxHashMap::remove(self, k)
300     }
301
302     #[inline(always)]
303     fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
304         self.iter()
305             .filter_map(move |(k, v)| f(k, &*v))
306             .collect()
307     }
308
309     #[inline(always)]
310     fn get_or<E>(
311         &self,
312         k: K,
313         vacant: impl FnOnce() -> Result<V, E>
314     ) -> Result<&V, E>
315     {
316         match self.get(&k) {
317             Some(v) => Ok(v),
318             None => {
319                 vacant()?;
320                 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
321             }
322         }
323     }
324
325     #[inline(always)]
326     fn get_mut_or<E>(
327         &mut self,
328         k: K,
329         vacant: impl FnOnce() -> Result<V, E>
330     ) -> Result<&mut V, E>
331     {
332         match self.entry(k) {
333             Entry::Occupied(e) => Ok(e.into_mut()),
334             Entry::Vacant(e) => {
335                 let v = vacant()?;
336                 Ok(e.insert(v))
337             }
338         }
339     }
340 }
341
342 type CompileTimeEvalContext<'a, 'mir, 'tcx> =
343     EvalContext<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>;
344
345 impl interpret::MayLeak for ! {
346     #[inline(always)]
347     fn may_leak(self) -> bool {
348         // `self` is uninhabited
349         self
350     }
351 }
352
353 impl<'a, 'mir, 'tcx> interpret::Machine<'a, 'mir, 'tcx>
354     for CompileTimeInterpreter<'a, 'mir, 'tcx>
355 {
356     type MemoryKinds = !;
357     type PointerTag = ();
358
359     type FrameExtra = ();
360     type MemoryExtra = ();
361     type AllocExtra = ();
362
363     type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation)>;
364
365     const STATIC_KIND: Option<!> = None; // no copying of statics allowed
366
367     #[inline(always)]
368     fn enforce_validity(_ecx: &EvalContext<'a, 'mir, 'tcx, Self>) -> bool {
369         false // for now, we don't enforce validity
370     }
371
372     fn find_fn(
373         ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
374         instance: ty::Instance<'tcx>,
375         args: &[OpTy<'tcx>],
376         dest: Option<PlaceTy<'tcx>>,
377         ret: Option<mir::BasicBlock>,
378     ) -> EvalResult<'tcx, Option<&'mir mir::Mir<'tcx>>> {
379         debug!("eval_fn_call: {:?}", instance);
380         // Execution might have wandered off into other crates, so we cannot to a stability-
381         // sensitive check here.  But we can at least rule out functions that are not const
382         // at all.
383         if !ecx.tcx.is_const_fn_raw(instance.def_id()) {
384             // Some functions we support even if they are non-const -- but avoid testing
385             // that for const fn!  We certainly do *not* want to actually call the fn
386             // though, so be sure we return here.
387             return if ecx.hook_fn(instance, args, dest)? {
388                 ecx.goto_block(ret)?; // fully evaluated and done
389                 Ok(None)
390             } else {
391                 err!(MachineError(format!("calling non-const function `{}`", instance)))
392             };
393         }
394         // This is a const fn. Call it.
395         Ok(Some(match ecx.load_mir(instance.def) {
396             Ok(mir) => mir,
397             Err(err) => {
398                 if let EvalErrorKind::NoMirFor(ref path) = err.kind {
399                     return Err(
400                         ConstEvalError::NeedsRfc(format!("calling extern function `{}`", path))
401                             .into(),
402                     );
403                 }
404                 return Err(err);
405             }
406         }))
407     }
408
409     fn call_intrinsic(
410         ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
411         instance: ty::Instance<'tcx>,
412         args: &[OpTy<'tcx>],
413         dest: PlaceTy<'tcx>,
414     ) -> EvalResult<'tcx> {
415         if ecx.emulate_intrinsic(instance, args, dest)? {
416             return Ok(());
417         }
418         // An intrinsic that we do not support
419         let intrinsic_name = &ecx.tcx.item_name(instance.def_id()).as_str()[..];
420         Err(
421             ConstEvalError::NeedsRfc(format!("calling intrinsic `{}`", intrinsic_name)).into()
422         )
423     }
424
425     fn ptr_op(
426         _ecx: &EvalContext<'a, 'mir, 'tcx, Self>,
427         _bin_op: mir::BinOp,
428         _left: Scalar,
429         _left_layout: TyLayout<'tcx>,
430         _right: Scalar,
431         _right_layout: TyLayout<'tcx>,
432     ) -> EvalResult<'tcx, (Scalar, bool)> {
433         Err(
434             ConstEvalError::NeedsRfc("pointer arithmetic or comparison".to_string()).into(),
435         )
436     }
437
438     fn find_foreign_static(
439         _def_id: DefId,
440         _tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
441         _memory_extra: &(),
442     ) -> EvalResult<'tcx, Cow<'tcx, Allocation<Self::PointerTag>>> {
443         err!(ReadForeignStatic)
444     }
445
446     #[inline(always)]
447     fn adjust_static_allocation<'b>(
448         alloc: &'b Allocation,
449         _memory_extra: &(),
450     ) -> Cow<'b, Allocation<Self::PointerTag>> {
451         // We do not use a tag so we can just cheaply forward the reference
452         Cow::Borrowed(alloc)
453     }
454
455     fn box_alloc(
456         _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
457         _dest: PlaceTy<'tcx>,
458     ) -> EvalResult<'tcx> {
459         Err(
460             ConstEvalError::NeedsRfc("heap allocations via `box` keyword".to_string()).into(),
461         )
462     }
463
464     fn before_terminator(ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>) -> EvalResult<'tcx> {
465         {
466             let steps = &mut ecx.machine.steps_since_detector_enabled;
467
468             *steps += 1;
469             if *steps < 0 {
470                 return Ok(());
471             }
472
473             *steps %= DETECTOR_SNAPSHOT_PERIOD;
474             if *steps != 0 {
475                 return Ok(());
476             }
477         }
478
479         let span = ecx.frame().span;
480         ecx.machine.loop_detector.observe_and_analyze(
481             &ecx.tcx,
482             span,
483             &ecx.memory,
484             &ecx.stack[..],
485         )
486     }
487
488     #[inline(always)]
489     fn tag_new_allocation(
490         _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
491         ptr: Pointer,
492         _kind: MemoryKind<Self::MemoryKinds>,
493     ) -> Pointer {
494         ptr
495     }
496
497     #[inline(always)]
498     fn stack_push(
499         _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
500     ) -> EvalResult<'tcx> {
501         Ok(())
502     }
503
504     /// Called immediately before a stack frame gets popped
505     #[inline(always)]
506     fn stack_pop(
507         _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
508         _extra: (),
509     ) -> EvalResult<'tcx> {
510         Ok(())
511     }
512 }
513
514 /// Project to a field of a (variant of a) const
515 pub fn const_field<'a, 'tcx>(
516     tcx: TyCtxt<'a, 'tcx, 'tcx>,
517     param_env: ty::ParamEnv<'tcx>,
518     instance: ty::Instance<'tcx>,
519     variant: Option<VariantIdx>,
520     field: mir::Field,
521     value: &'tcx ty::Const<'tcx>,
522 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
523     trace!("const_field: {:?}, {:?}, {:?}", instance, field, value);
524     let ecx = mk_eval_cx(tcx, instance, param_env).unwrap();
525     let result = (|| {
526         // get the operand again
527         let op = const_to_op(&ecx, value)?;
528         // downcast
529         let down = match variant {
530             None => op,
531             Some(variant) => ecx.operand_downcast(op, variant)?
532         };
533         // then project
534         let field = ecx.operand_field(down, field.index() as u64)?;
535         // and finally move back to the const world, always normalizing because
536         // this is not called for statics.
537         op_to_const(&ecx, field, true)
538     })();
539     result.map_err(|error| {
540         let err = error_to_const_error(&ecx, error);
541         err.report_as_error(ecx.tcx, "could not access field of constant");
542         ErrorHandled::Reported
543     })
544 }
545
546 pub fn const_variant_index<'a, 'tcx>(
547     tcx: TyCtxt<'a, 'tcx, 'tcx>,
548     param_env: ty::ParamEnv<'tcx>,
549     instance: ty::Instance<'tcx>,
550     val: &'tcx ty::Const<'tcx>,
551 ) -> EvalResult<'tcx, VariantIdx> {
552     trace!("const_variant_index: {:?}, {:?}", instance, val);
553     let ecx = mk_eval_cx(tcx, instance, param_env).unwrap();
554     let op = const_to_op(&ecx, val)?;
555     Ok(ecx.read_discriminant(op)?.1)
556 }
557
558 pub fn error_to_const_error<'a, 'mir, 'tcx>(
559     ecx: &EvalContext<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>,
560     mut error: EvalError<'tcx>
561 ) -> ConstEvalErr<'tcx> {
562     error.print_backtrace();
563     let stacktrace = ecx.generate_stacktrace(None);
564     ConstEvalErr { error: error.kind, stacktrace, span: ecx.tcx.span }
565 }
566
567 fn validate_and_turn_into_const<'a, 'tcx>(
568     tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
569     constant: RawConst<'tcx>,
570     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
571 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
572     let cid = key.value;
573     let ecx = mk_eval_cx(tcx, cid.instance, key.param_env).unwrap();
574     let val = (|| {
575         let op = ecx.raw_const_to_mplace(constant)?.into();
576         // FIXME: Once the visitor infrastructure landed, change validation to
577         // work directly on `MPlaceTy`.
578         let mut ref_tracking = RefTracking::new(op);
579         while let Some((op, path)) = ref_tracking.todo.pop() {
580             ecx.validate_operand(
581                 op,
582                 path,
583                 Some(&mut ref_tracking),
584                 /* const_mode */ true,
585             )?;
586         }
587         // Now that we validated, turn this into a proper constant
588         let def_id = cid.instance.def.def_id();
589         let normalize = tcx.is_static(def_id).is_none() && cid.promoted.is_none();
590         op_to_const(&ecx, op, normalize)
591     })();
592
593     val.map_err(|error| {
594         let err = error_to_const_error(&ecx, error);
595         match err.struct_error(ecx.tcx, "it is undefined behavior to use this value") {
596             Ok(mut diag) => {
597                 diag.note("The rules on what exactly is undefined behavior aren't clear, \
598                     so this check might be overzealous. Please open an issue on the rust compiler \
599                     repository if you believe it should not be considered undefined behavior",
600                 );
601                 diag.emit();
602                 ErrorHandled::Reported
603             }
604             Err(err) => err,
605         }
606     })
607 }
608
609 pub fn const_eval_provider<'a, 'tcx>(
610     tcx: TyCtxt<'a, 'tcx, 'tcx>,
611     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
612 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
613     // see comment in const_eval_provider for what we're doing here
614     if key.param_env.reveal == Reveal::All {
615         let mut key = key.clone();
616         key.param_env.reveal = Reveal::UserFacing;
617         match tcx.const_eval(key) {
618             // try again with reveal all as requested
619             Err(ErrorHandled::TooGeneric) => {
620                 // Promoteds should never be "too generic" when getting evaluated.
621                 // They either don't get evaluated, or we are in a monomorphic context
622                 assert!(key.value.promoted.is_none());
623             },
624             // dedupliate calls
625             other => return other,
626         }
627     }
628     tcx.const_eval_raw(key).and_then(|val| {
629         validate_and_turn_into_const(tcx, val, key)
630     })
631 }
632
633 pub fn const_eval_raw_provider<'a, 'tcx>(
634     tcx: TyCtxt<'a, 'tcx, 'tcx>,
635     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
636 ) -> ::rustc::mir::interpret::ConstEvalRawResult<'tcx> {
637     // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
638     // reporting the same error twice here. To resolve this, we check whether we can evaluate the
639     // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
640     // computed. For a large percentage of constants that will already have succeeded. Only
641     // associated constants of generic functions will fail due to not enough monomorphization
642     // information being available.
643
644     // In case we fail in the `UserFacing` variant, we just do the real computation.
645     if key.param_env.reveal == Reveal::All {
646         let mut key = key.clone();
647         key.param_env.reveal = Reveal::UserFacing;
648         match tcx.const_eval_raw(key) {
649             // try again with reveal all as requested
650             Err(ErrorHandled::TooGeneric) => {},
651             // dedupliate calls
652             other => return other,
653         }
654     }
655     // the first trace is for replicating an ice
656     // There's no tracking issue, but the next two lines concatenated link to the discussion on
657     // zulip. It's not really possible to test this, because it doesn't show up in diagnostics
658     // or MIR.
659     // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
660     // subject/anon_const_instance_printing/near/135980032
661     trace!("const eval: {}", key.value.instance);
662     trace!("const eval: {:?}", key);
663
664     let cid = key.value;
665     let def_id = cid.instance.def.def_id();
666
667     if let Some(id) = tcx.hir().as_local_node_id(def_id) {
668         let tables = tcx.typeck_tables_of(def_id);
669
670         // Do match-check before building MIR
671         if let Err(ErrorReported) = tcx.check_match(def_id) {
672             return Err(ErrorHandled::Reported)
673         }
674
675         if let hir::BodyOwnerKind::Const = tcx.hir().body_owner_kind(id) {
676             tcx.mir_const_qualif(def_id);
677         }
678
679         // Do not continue into miri if typeck errors occurred; it will fail horribly
680         if tables.tainted_by_errors {
681             return Err(ErrorHandled::Reported)
682         }
683     };
684
685     let (res, ecx) = eval_body_and_ecx(tcx, cid, None, key.param_env);
686     res.and_then(|place| {
687         Ok(RawConst {
688             alloc_id: place.to_ptr().expect("we allocated this ptr!").alloc_id,
689             ty: place.layout.ty
690         })
691     }).map_err(|error| {
692         let err = error_to_const_error(&ecx, error);
693         // errors in statics are always emitted as fatal errors
694         if tcx.is_static(def_id).is_some() {
695             let reported_err = err.report_as_error(ecx.tcx,
696                                                    "could not evaluate static initializer");
697             // Ensure that if the above error was either `TooGeneric` or `Reported`
698             // an error must be reported.
699             if tcx.sess.err_count() == 0 {
700                 tcx.sess.delay_span_bug(err.span,
701                                         &format!("static eval failure did not emit an error: {:#?}",
702                                                  reported_err));
703             }
704             reported_err
705         } else if def_id.is_local() {
706             // constant defined in this crate, we can figure out a lint level!
707             match tcx.describe_def(def_id) {
708                 // constants never produce a hard error at the definition site. Anything else is
709                 // a backwards compatibility hazard (and will break old versions of winapi for sure)
710                 //
711                 // note that validation may still cause a hard error on this very same constant,
712                 // because any code that existed before validation could not have failed validation
713                 // thus preventing such a hard error from being a backwards compatibility hazard
714                 Some(Def::Const(_)) | Some(Def::AssociatedConst(_)) => {
715                     let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
716                     err.report_as_lint(
717                         tcx.at(tcx.def_span(def_id)),
718                         "any use of this value will cause an error",
719                         node_id,
720                     )
721                 },
722                 // promoting runtime code is only allowed to error if it references broken constants
723                 // any other kind of error will be reported to the user as a deny-by-default lint
724                 _ => if let Some(p) = cid.promoted {
725                     let span = tcx.optimized_mir(def_id).promoted[p].span;
726                     if let EvalErrorKind::ReferencedConstant = err.error {
727                         err.report_as_error(
728                             tcx.at(span),
729                             "evaluation of constant expression failed",
730                         )
731                     } else {
732                         err.report_as_lint(
733                             tcx.at(span),
734                             "reaching this expression at runtime will panic or abort",
735                             tcx.hir().as_local_node_id(def_id).unwrap(),
736                         )
737                     }
738                 // anything else (array lengths, enum initializers, constant patterns) are reported
739                 // as hard errors
740                 } else {
741                     err.report_as_error(
742                         ecx.tcx,
743                         "evaluation of constant value failed",
744                     )
745                 },
746             }
747         } else {
748             // use of broken constant from other crate
749             err.report_as_error(ecx.tcx, "could not evaluate constant")
750         }
751     })
752 }