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}