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