rustc_const_eval/interpret/
util.rs

1use rustc_hir::def_id::LocalDefId;
2use rustc_middle::mir;
3use rustc_middle::mir::interpret::{AllocInit, Allocation, InterpResult, Pointer};
4use rustc_middle::ty::layout::TyAndLayout;
5use rustc_middle::ty::{TyCtxt, TypeVisitable, TypeVisitableExt};
6use tracing::debug;
7
8use super::{InterpCx, MPlaceTy, MemoryKind, interp_ok, throw_inval};
9use crate::const_eval::{CompileTimeInterpCx, CompileTimeMachine, InterpretationResult};
10
11/// Checks whether a type contains generic parameters which must be instantiated.
12///
13/// In case it does, returns a `TooGeneric` const eval error.
14pub(crate) fn ensure_monomorphic_enough<'tcx, T>(_tcx: TyCtxt<'tcx>, ty: T) -> InterpResult<'tcx>
15where
16    T: TypeVisitable<TyCtxt<'tcx>>,
17{
18    debug!("ensure_monomorphic_enough: ty={:?}", ty);
19    if ty.has_param() {
20        throw_inval!(TooGeneric);
21    }
22    interp_ok(())
23}
24
25impl<'tcx> InterpretationResult<'tcx> for mir::interpret::ConstAllocation<'tcx> {
26    fn make_result(
27        mplace: MPlaceTy<'tcx>,
28        ecx: &mut InterpCx<'tcx, CompileTimeMachine<'tcx>>,
29    ) -> Self {
30        let alloc_id = mplace.ptr().provenance.unwrap().alloc_id();
31        let alloc = ecx.memory.alloc_map.swap_remove(&alloc_id).unwrap().1;
32        ecx.tcx.mk_const_alloc(alloc)
33    }
34}
35
36pub(crate) fn create_static_alloc<'tcx>(
37    ecx: &mut CompileTimeInterpCx<'tcx>,
38    static_def_id: LocalDefId,
39    layout: TyAndLayout<'tcx>,
40) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
41    let alloc = Allocation::try_new(layout.size, layout.align.abi, AllocInit::Uninit, ())?;
42    let alloc_id = ecx.tcx.reserve_and_set_static_alloc(static_def_id.into());
43    assert_eq!(ecx.machine.static_root_ids, None);
44    ecx.machine.static_root_ids = Some((alloc_id, static_def_id));
45    assert!(ecx.memory.alloc_map.insert(alloc_id, (MemoryKind::Stack, alloc)).is_none());
46    interp_ok(ecx.ptr_to_mplace(Pointer::from(alloc_id).into(), layout))
47}
48
49/// A marker trait returned by [crate::interpret::Machine::enter_trace_span], identifying either a
50/// real [tracing::span::EnteredSpan] in case tracing is enabled, or the dummy type `()` when
51/// tracing is disabled.
52pub trait EnteredTraceSpan {}
53impl EnteredTraceSpan for () {}
54impl EnteredTraceSpan for tracing::span::EnteredSpan {}
55
56/// Shortand for calling [crate::interpret::Machine::enter_trace_span] on a [tracing::info_span].
57/// This is supposed to be compiled out when [crate::interpret::Machine::enter_trace_span] has the
58/// default implementation (i.e. when it does not actually enter the span but instead returns `()`).
59/// Note: the result of this macro **must be used** because the span is exited when it's dropped.
60#[macro_export]
61macro_rules! enter_trace_span {
62    ($machine:ident, $($tt:tt)*) => {
63        $machine::enter_trace_span(|| tracing::info_span!($($tt)*))
64    }
65}