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