1 // Not in interpret to make sure we do not use private implementation details
5 use std::borrow::{Borrow, Cow};
7 use std::collections::hash_map::Entry;
8 use std::convert::TryInto;
10 use rustc::hir::def::DefKind;
11 use rustc::hir::def_id::DefId;
12 use rustc::mir::interpret::{ConstEvalErr, ErrorHandled, ScalarMaybeUndef};
14 use rustc::ty::{self, Ty, TyCtxt, subst::Subst};
15 use rustc::ty::layout::{self, HasTyCtxt, LayoutOf, VariantIdx};
16 use rustc::traits::Reveal;
17 use rustc_data_structures::fx::FxHashMap;
18 use crate::interpret::eval_nullary_intrinsic;
20 use syntax::{source_map::{Span, DUMMY_SP}, symbol::Symbol};
22 use crate::interpret::{self,
23 PlaceTy, MPlaceTy, OpTy, ImmTy, Immediate, Scalar, Pointer,
24 RawConst, ConstValue, Machine,
25 InterpResult, InterpErrorInfo, GlobalId, InterpCx, StackPopCleanup, AssertMessage,
26 Allocation, AllocId, MemoryKind, Memory,
27 snapshot, RefTracking, intern_const_alloc_recursive,
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;
37 /// The `InterpCx` is only meant to be used to do field and index projections into constants for
38 /// `simd_shuffle` and const patterns in match arms.
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 fn mk_eval_cx<'mir, 'tcx>(
47 param_env: ty::ParamEnv<'tcx>,
48 ) -> CompileTimeEvalContext<'mir, 'tcx> {
49 debug!("mk_eval_cx: {:?}", param_env);
50 InterpCx::new(tcx.at(span), param_env, CompileTimeInterpreter::new(), Default::default())
54 ecx: &CompileTimeEvalContext<'_, 'tcx>,
56 ) -> &'tcx ty::Const<'tcx> {
57 // We do not have value optimizations for everything.
58 // Only scalars and slices, since they are very common.
59 // Note that further down we turn scalars of undefined bits back to `ByRef`. These can result
60 // from scalar unions that are initialized with one of their zero sized variants. We could
61 // instead allow `ConstValue::Scalar` to store `ScalarMaybeUndef`, but that would affect all
62 // the usual cases of extracting e.g. a `usize`, without there being a real use case for the
64 let try_as_immediate = match op.layout.abi {
65 layout::Abi::Scalar(..) => true,
66 layout::Abi::ScalarPair(..) => match op.layout.ty.kind {
67 ty::Ref(_, inner, _) => match inner.kind {
68 ty::Slice(elem) => elem == ecx.tcx.types.u8,
76 let immediate = if try_as_immediate {
77 Err(ecx.read_immediate(op).expect("normalization works on validated constants"))
79 // It is guaranteed that any non-slice scalar pair is actually ByRef here.
80 // When we come back from raw const eval, we are always by-ref. The only way our op here is
81 // by-val is if we are in const_field, i.e., if this is (a field of) something that we
82 // "tried to make immediate" before. We wouldn't do that for non-slice scalar pairs or
83 // structs containing such.
86 let val = match immediate {
88 let ptr = mplace.ptr.to_ptr().unwrap();
89 let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
90 ConstValue::ByRef { alloc, offset: ptr.offset }
92 // see comment on `let try_as_immediate` above
93 Err(ImmTy { imm: Immediate::Scalar(x), .. }) => match x {
94 ScalarMaybeUndef::Scalar(s) => ConstValue::Scalar(s),
95 ScalarMaybeUndef::Undef => {
96 // When coming out of "normal CTFE", we'll always have an `Indirect` operand as
97 // argument and we will not need this. The only way we can already have an
98 // `Immediate` is when we are called from `const_field`, and that `Immediate`
99 // comes from a constant so it can happen have `Undef`, because the indirect
100 // memory that was read had undefined bytes.
101 let mplace = op.assert_mem_place();
102 let ptr = mplace.ptr.to_ptr().unwrap();
103 let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
104 ConstValue::ByRef { alloc, offset: ptr.offset }
107 Err(ImmTy { imm: Immediate::ScalarPair(a, b), .. }) => {
108 let (data, start) = match a.not_undef().unwrap() {
109 Scalar::Ptr(ptr) => (
110 ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id),
113 Scalar::Raw { .. } => (
114 ecx.tcx.intern_const_alloc(Allocation::from_byte_aligned_bytes(
120 let len = b.to_machine_usize(&ecx.tcx.tcx).unwrap();
121 let start = start.try_into().unwrap();
122 let len: usize = len.try_into().unwrap();
130 ecx.tcx.mk_const(ty::Const { val: ty::ConstKind::Value(val), ty: op.layout.ty })
133 // Returns a pointer to where the result lives
134 fn eval_body_using_ecx<'mir, 'tcx>(
135 ecx: &mut CompileTimeEvalContext<'mir, 'tcx>,
137 body: &'mir mir::Body<'tcx>,
138 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
139 debug!("eval_body_using_ecx: {:?}, {:?}", cid, ecx.param_env);
140 let tcx = ecx.tcx.tcx;
141 let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?;
142 assert!(!layout.is_unsized());
143 let ret = ecx.allocate(layout, MemoryKind::Stack);
145 let name = ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()));
146 let prom = cid.promoted.map_or(String::new(), |p| format!("::promoted[{:?}]", p));
147 trace!("eval_body_using_ecx: pushing stack frame for global: {}{}", name, prom);
149 // Assert all args (if any) are zero-sized types; `eval_body_using_ecx` doesn't
150 // make sense if the body is expecting nontrivial arguments.
151 // (The alternative would be to use `eval_fn_call` with an args slice.)
152 for arg in body.args_iter() {
153 let decl = body.local_decls.get(arg).expect("arg missing from local_decls");
154 let layout = ecx.layout_of(decl.ty.subst(tcx, cid.instance.substs))?;
155 assert!(layout.is_zst())
158 ecx.push_stack_frame(
163 StackPopCleanup::None { cleanup: false },
166 // The main interpreter loop.
170 intern_const_alloc_recursive(ecx, tcx.static_mutability(cid.instance.def_id()), ret)?;
172 debug!("eval_body_using_ecx done: {:?}", *ret);
176 #[derive(Clone, Debug)]
177 pub enum ConstEvalError {
181 impl<'tcx> Into<InterpErrorInfo<'tcx>> for ConstEvalError {
182 fn into(self) -> InterpErrorInfo<'tcx> {
183 err_unsup!(Unsupported(self.to_string())).into()
187 impl fmt::Display for ConstEvalError {
188 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189 use self::ConstEvalError::*;
191 NeedsRfc(ref msg) => {
194 "\"{}\" needs an rfc before being allowed inside constants",
202 impl Error for ConstEvalError {
203 fn description(&self) -> &str {
204 use self::ConstEvalError::*;
206 NeedsRfc(_) => "this feature needs an rfc before being allowed inside constants",
210 fn cause(&self) -> Option<&dyn Error> {
215 // Extra machine state for CTFE, and the Machine instance
216 pub struct CompileTimeInterpreter<'mir, 'tcx> {
217 /// When this value is negative, it indicates the number of interpreter
218 /// steps *until* the loop detector is enabled. When it is positive, it is
219 /// the number of steps after the detector has been enabled modulo the loop
221 pub(super) steps_since_detector_enabled: isize,
223 /// Extra state to detect loops.
224 pub(super) loop_detector: snapshot::InfiniteLoopDetector<'mir, 'tcx>,
227 impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> {
229 CompileTimeInterpreter {
230 loop_detector: Default::default(),
231 steps_since_detector_enabled: -STEPS_UNTIL_DETECTOR_ENABLED,
236 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
238 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
241 FxHashMap::contains_key(self, k)
245 fn insert(&mut self, k: K, v: V) -> Option<V>
247 FxHashMap::insert(self, k, v)
251 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
254 FxHashMap::remove(self, k)
258 fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
260 .filter_map(move |(k, v)| f(k, &*v))
268 vacant: impl FnOnce() -> Result<V, E>
275 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
284 vacant: impl FnOnce() -> Result<V, E>
285 ) -> Result<&mut V, E>
287 match self.entry(k) {
288 Entry::Occupied(e) => Ok(e.into_mut()),
289 Entry::Vacant(e) => {
297 crate type CompileTimeEvalContext<'mir, 'tcx> =
298 InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>;
300 impl interpret::MayLeak for ! {
302 fn may_leak(self) -> bool {
303 // `self` is uninhabited
308 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> {
309 type MemoryKinds = !;
310 type PointerTag = ();
313 type FrameExtra = ();
314 type MemoryExtra = ();
315 type AllocExtra = ();
317 type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation)>;
319 const STATIC_KIND: Option<!> = None; // no copying of statics allowed
321 // We do not check for alignment to avoid having to carry an `Align`
322 // in `ConstValue::ByRef`.
323 const CHECK_ALIGN: bool = false;
326 fn enforce_validity(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
327 false // for now, we don't enforce validity
330 fn find_mir_or_eval_fn(
331 ecx: &mut InterpCx<'mir, 'tcx, Self>,
332 instance: ty::Instance<'tcx>,
334 ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
335 _unwind: Option<mir::BasicBlock> // unwinding is not supported in consts
336 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
337 debug!("find_mir_or_eval_fn: {:?}", instance);
339 // Only check non-glue functions
340 if let ty::InstanceDef::Item(def_id) = instance.def {
341 // Execution might have wandered off into other crates, so we cannot do a stability-
342 // sensitive check here. But we can at least rule out functions that are not const
344 if ecx.tcx.is_const_fn_raw(def_id) {
345 // If this function is a `const fn` then as an optimization we can query this
346 // evaluation immediately.
348 // For the moment we only do this for functions which take no arguments
349 // (or all arguments are ZSTs) so that we don't memoize too much.
351 // Because `#[track_caller]` adds an implicit non-ZST argument, we also cannot
352 // perform this optimization on items tagged with it.
353 let no_implicit_args = !instance.def.requires_caller_location(ecx.tcx());
354 if args.iter().all(|a| a.layout.is_zst()) && no_implicit_args {
355 let gid = GlobalId { instance, promoted: None };
356 ecx.eval_const_fn_call(gid, ret)?;
360 // Some functions we support even if they are non-const -- but avoid testing
361 // that for const fn! We certainly do *not* want to actually call the fn
362 // though, so be sure we return here.
363 return if ecx.hook_panic_fn(instance, args, ret)? {
366 throw_unsup_format!("calling non-const function `{}`", instance)
370 // This is a const fn. Call it.
371 Ok(Some(match ecx.load_mir(instance.def, None) {
374 if let err_unsup!(NoMirFor(ref path)) = err.kind {
376 ConstEvalError::NeedsRfc(format!("calling extern function `{}`", path))
386 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
388 _args: &[OpTy<'tcx>],
389 _ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
390 _unwind: Option<mir::BasicBlock>
391 ) -> InterpResult<'tcx> {
396 ecx: &mut InterpCx<'mir, 'tcx, Self>,
398 instance: ty::Instance<'tcx>,
400 ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
401 _unwind: Option<mir::BasicBlock>
402 ) -> InterpResult<'tcx> {
403 if ecx.emulate_intrinsic(span, instance, args, ret)? {
406 // An intrinsic that we do not support
407 let intrinsic_name = ecx.tcx.item_name(instance.def_id());
409 ConstEvalError::NeedsRfc(format!("calling intrinsic `{}`", intrinsic_name)).into()
414 ecx: &mut InterpCx<'mir, 'tcx, Self>,
416 msg: &AssertMessage<'tcx>,
417 _unwind: Option<mir::BasicBlock>,
418 ) -> InterpResult<'tcx> {
419 use rustc::mir::interpret::PanicInfo::*;
421 BoundsCheck { ref len, ref index } => {
423 .read_immediate(ecx.eval_operand(len, None)?)
424 .expect("can't eval len")
426 .to_machine_usize(&*ecx)?;
428 .read_immediate(ecx.eval_operand(index, None)?)
429 .expect("can't eval index")
431 .to_machine_usize(&*ecx)?;
432 err_panic!(BoundsCheck { len, index })
434 Overflow(op) => err_panic!(Overflow(*op)),
435 OverflowNeg => err_panic!(OverflowNeg),
436 DivisionByZero => err_panic!(DivisionByZero),
437 RemainderByZero => err_panic!(RemainderByZero),
438 ResumedAfterReturn(generator_kind)
439 => err_panic!(ResumedAfterReturn(*generator_kind)),
440 ResumedAfterPanic(generator_kind)
441 => err_panic!(ResumedAfterPanic(*generator_kind)),
442 Panic { .. } => bug!("`Panic` variant cannot occur in MIR"),
448 _mem: &Memory<'mir, 'tcx, Self>,
450 ) -> InterpResult<'tcx, u64> {
452 ConstEvalError::NeedsRfc("pointer-to-integer cast".to_string()).into(),
457 _ecx: &InterpCx<'mir, 'tcx, Self>,
461 ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
463 ConstEvalError::NeedsRfc("pointer arithmetic or comparison".to_string()).into(),
467 fn find_foreign_static(
470 ) -> InterpResult<'tcx, Cow<'tcx, Allocation<Self::PointerTag>>> {
471 throw_unsup!(ReadForeignStatic)
475 fn init_allocation_extra<'b>(
478 alloc: Cow<'b, Allocation>,
479 _kind: Option<MemoryKind<!>>,
480 ) -> (Cow<'b, Allocation<Self::PointerTag>>, Self::PointerTag) {
481 // We do not use a tag so we can just cheaply forward the allocation
486 fn tag_static_base_pointer(
489 ) -> Self::PointerTag {
494 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
495 _dest: PlaceTy<'tcx>,
496 ) -> InterpResult<'tcx> {
498 ConstEvalError::NeedsRfc("heap allocations via `box` keyword".to_string()).into(),
502 fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
504 let steps = &mut ecx.machine.steps_since_detector_enabled;
511 *steps %= DETECTOR_SNAPSHOT_PERIOD;
517 let span = ecx.frame().span;
518 ecx.machine.loop_detector.observe_and_analyze(
527 fn stack_push(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
532 /// Extracts a field of a (variant of a) const.
533 // this function uses `unwrap` copiously, because an already validated constant must have valid
534 // fields and can thus never fail outside of compiler bugs
535 pub fn const_field<'tcx>(
537 param_env: ty::ParamEnv<'tcx>,
538 variant: Option<VariantIdx>,
540 value: &'tcx ty::Const<'tcx>,
541 ) -> &'tcx ty::Const<'tcx> {
542 trace!("const_field: {:?}, {:?}", field, value);
543 let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
544 // get the operand again
545 let op = ecx.eval_const_to_op(value, None).unwrap();
547 let down = match variant {
549 Some(variant) => ecx.operand_downcast(op, variant).unwrap(),
552 let field = ecx.operand_field(down, field.index() as u64).unwrap();
553 // and finally move back to the const world, always normalizing because
554 // this is not called for statics.
555 op_to_const(&ecx, field)
558 pub fn const_caller_location<'tcx>(
560 (file, line, col): (Symbol, u32, u32),
561 ) -> &'tcx ty::Const<'tcx> {
562 trace!("const_caller_location: {}:{}:{}", file, line, col);
563 let mut ecx = mk_eval_cx(tcx, DUMMY_SP, ty::ParamEnv::reveal_all());
565 let loc_ty = tcx.caller_location_ty();
566 let loc_place = ecx.alloc_caller_location(file, line, col);
567 intern_const_alloc_recursive(&mut ecx, None, loc_place).unwrap();
568 let loc_const = ty::Const {
570 val: ty::ConstKind::Value(ConstValue::Scalar(loc_place.ptr.into())),
573 tcx.mk_const(loc_const)
576 // this function uses `unwrap` copiously, because an already validated constant must have valid
577 // fields and can thus never fail outside of compiler bugs
578 pub fn const_variant_index<'tcx>(
580 param_env: ty::ParamEnv<'tcx>,
581 val: &'tcx ty::Const<'tcx>,
583 trace!("const_variant_index: {:?}", val);
584 let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
585 let op = ecx.eval_const_to_op(val, None).unwrap();
586 ecx.read_discriminant(op).unwrap().1
589 /// Turn an interpreter error into something to report to the user.
590 /// As a side-effect, if RUSTC_CTFE_BACKTRACE is set, this prints the backtrace.
591 /// Should be called only if the error is actually going to to be reported!
592 pub fn error_to_const_error<'mir, 'tcx, M: Machine<'mir, 'tcx>>(
593 ecx: &InterpCx<'mir, 'tcx, M>,
594 mut error: InterpErrorInfo<'tcx>,
595 ) -> ConstEvalErr<'tcx> {
596 error.print_backtrace();
597 let stacktrace = ecx.generate_stacktrace(None);
598 ConstEvalErr { error: error.kind, stacktrace, span: ecx.tcx.span }
601 pub fn note_on_undefined_behavior_error() -> &'static str {
602 "The rules on what exactly is undefined behavior aren't clear, \
603 so this check might be overzealous. Please open an issue on the rustc \
604 repository if you believe it should not be considered undefined behavior."
607 fn validate_and_turn_into_const<'tcx>(
609 constant: RawConst<'tcx>,
610 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
611 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
613 let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env);
615 let mplace = ecx.raw_const_to_mplace(constant)?;
616 let mut ref_tracking = RefTracking::new(mplace);
617 while let Some((mplace, path)) = ref_tracking.todo.pop() {
618 ecx.validate_operand(
621 Some(&mut ref_tracking),
624 // Now that we validated, turn this into a proper constant.
625 // Statics/promoteds are always `ByRef`, for the rest `op_to_const` decides
626 // whether they become immediates.
627 let def_id = cid.instance.def.def_id();
628 if tcx.is_static(def_id) || cid.promoted.is_some() {
629 let ptr = mplace.ptr.to_ptr()?;
630 Ok(tcx.mk_const(ty::Const {
631 val: ty::ConstKind::Value(ConstValue::ByRef {
632 alloc: ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id),
635 ty: mplace.layout.ty,
638 Ok(op_to_const(&ecx, mplace.into()))
642 val.map_err(|error| {
643 let err = error_to_const_error(&ecx, error);
644 match err.struct_error(ecx.tcx, "it is undefined behavior to use this value") {
646 diag.note(note_on_undefined_behavior_error());
648 ErrorHandled::Reported
655 pub fn const_eval_validated_provider<'tcx>(
657 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
658 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
659 // see comment in const_eval_raw_provider for what we're doing here
660 if key.param_env.reveal == Reveal::All {
661 let mut key = key.clone();
662 key.param_env.reveal = Reveal::UserFacing;
663 match tcx.const_eval_validated(key) {
664 // try again with reveal all as requested
665 Err(ErrorHandled::TooGeneric) => {
666 // Promoteds should never be "too generic" when getting evaluated.
667 // They either don't get evaluated, or we are in a monomorphic context
668 assert!(key.value.promoted.is_none());
671 other => return other,
675 // We call `const_eval` for zero arg intrinsics, too, in order to cache their value.
676 // Catch such calls and evaluate them instead of trying to load a constant's MIR.
677 if let ty::InstanceDef::Intrinsic(def_id) = key.value.instance.def {
678 let ty = key.value.instance.ty(tcx);
679 let substs = match ty.kind {
680 ty::FnDef(_, substs) => substs,
681 _ => bug!("intrinsic with type {:?}", ty),
683 return eval_nullary_intrinsic(tcx, key.param_env, def_id, substs)
685 let span = tcx.def_span(def_id);
686 let error = ConstEvalErr { error: error.kind, stacktrace: vec![], span };
687 error.report_as_error(tcx.at(span), "could not evaluate nullary intrinsic")
691 tcx.const_eval_raw(key).and_then(|val| {
692 validate_and_turn_into_const(tcx, val, key)
696 pub fn const_eval_raw_provider<'tcx>(
698 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
699 ) -> ::rustc::mir::interpret::ConstEvalRawResult<'tcx> {
700 // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
701 // reporting the same error twice here. To resolve this, we check whether we can evaluate the
702 // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
703 // computed. For a large percentage of constants that will already have succeeded. Only
704 // associated constants of generic functions will fail due to not enough monomorphization
705 // information being available.
707 // In case we fail in the `UserFacing` variant, we just do the real computation.
708 if key.param_env.reveal == Reveal::All {
709 let mut key = key.clone();
710 key.param_env.reveal = Reveal::UserFacing;
711 match tcx.const_eval_raw(key) {
712 // try again with reveal all as requested
713 Err(ErrorHandled::TooGeneric) => {},
715 other => return other,
718 if cfg!(debug_assertions) {
719 // Make sure we format the instance even if we do not print it.
720 // This serves as a regression test against an ICE on printing.
721 // The next two lines concatenated contain some discussion:
722 // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
723 // subject/anon_const_instance_printing/near/135980032
724 let instance = key.value.instance.to_string();
725 trace!("const eval: {:?} ({})", key, instance);
729 let def_id = cid.instance.def.def_id();
731 if def_id.is_local() && tcx.typeck_tables_of(def_id).tainted_by_errors {
732 return Err(ErrorHandled::Reported);
735 let span = tcx.def_span(cid.instance.def_id());
736 let mut ecx = InterpCx::new(
739 CompileTimeInterpreter::new(),
743 let res = ecx.load_mir(cid.instance.def, cid.promoted);
745 |body| eval_body_using_ecx(&mut ecx, cid, *body)
748 alloc_id: place.ptr.assert_ptr().alloc_id,
752 let err = error_to_const_error(&ecx, error);
753 // errors in statics are always emitted as fatal errors
754 if tcx.is_static(def_id) {
755 // Ensure that if the above error was either `TooGeneric` or `Reported`
756 // an error must be reported.
757 let v = err.report_as_error(ecx.tcx, "could not evaluate static initializer");
758 tcx.sess.delay_span_bug(
760 &format!("static eval failure did not emit an error: {:#?}", v)
763 } else if def_id.is_local() {
764 // constant defined in this crate, we can figure out a lint level!
765 match tcx.def_kind(def_id) {
766 // constants never produce a hard error at the definition site. Anything else is
767 // a backwards compatibility hazard (and will break old versions of winapi for sure)
769 // note that validation may still cause a hard error on this very same constant,
770 // because any code that existed before validation could not have failed validation
771 // thus preventing such a hard error from being a backwards compatibility hazard
772 Some(DefKind::Const) | Some(DefKind::AssocConst) => {
773 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
775 tcx.at(tcx.def_span(def_id)),
776 "any use of this value will cause an error",
781 // promoting runtime code is only allowed to error if it references broken constants
782 // any other kind of error will be reported to the user as a deny-by-default lint
783 _ => if let Some(p) = cid.promoted {
784 let span = tcx.promoted_mir(def_id)[p].span;
785 if let err_inval!(ReferencedConstant) = err.error {
788 "evaluation of constant expression failed",
793 "reaching this expression at runtime will panic or abort",
794 tcx.hir().as_local_hir_id(def_id).unwrap(),
798 // anything else (array lengths, enum initializers, constant patterns) are reported
803 "evaluation of constant value failed",
808 // use of broken constant from other crate
809 err.report_as_error(ecx.tcx, "could not evaluate constant")