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