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