]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_const_eval/src/const_eval/mod.rs
New upstream version 1.62.1+dfsg1
[rustc.git] / compiler / rustc_const_eval / src / const_eval / mod.rs
1 // Not in interpret to make sure we do not use private implementation details
2
3 use std::convert::TryFrom;
4
5 use rustc_hir::Mutability;
6 use rustc_middle::mir;
7 use rustc_middle::ty::{self, TyCtxt};
8 use rustc_span::{source_map::DUMMY_SP, symbol::Symbol};
9
10 use crate::interpret::{
11 intern_const_alloc_recursive, ConstValue, InternKind, InterpCx, InterpResult, MemPlaceMeta,
12 Scalar,
13 };
14
15 mod error;
16 mod eval_queries;
17 mod fn_queries;
18 mod machine;
19 mod valtrees;
20
21 pub use error::*;
22 pub use eval_queries::*;
23 pub use fn_queries::*;
24 pub use machine::*;
25 pub(crate) use valtrees::{const_to_valtree, valtree_to_const_value};
26
27 pub(crate) fn const_caller_location(
28 tcx: TyCtxt<'_>,
29 (file, line, col): (Symbol, u32, u32),
30 ) -> ConstValue<'_> {
31 trace!("const_caller_location: {}:{}:{}", file, line, col);
32 let mut ecx = mk_eval_cx(tcx, DUMMY_SP, ty::ParamEnv::reveal_all(), false);
33
34 let loc_place = ecx.alloc_caller_location(file, line, col);
35 if intern_const_alloc_recursive(&mut ecx, InternKind::Constant, &loc_place).is_err() {
36 bug!("intern_const_alloc_recursive should not error in this case")
37 }
38 ConstValue::Scalar(Scalar::from_maybe_pointer(loc_place.ptr, &tcx))
39 }
40
41 /// This function should never fail for validated constants. However, it is also invoked from the
42 /// pretty printer which might attempt to format invalid constants and in that case it might fail.
43 pub(crate) fn try_destructure_const<'tcx>(
44 tcx: TyCtxt<'tcx>,
45 param_env: ty::ParamEnv<'tcx>,
46 val: ty::Const<'tcx>,
47 ) -> InterpResult<'tcx, mir::DestructuredConst<'tcx>> {
48 trace!("destructure_const: {:?}", val);
49 let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false);
50 let op = ecx.const_to_op(val, None)?;
51
52 // We go to `usize` as we cannot allocate anything bigger anyway.
53 let (field_count, variant, down) = match val.ty().kind() {
54 ty::Array(_, len) => (usize::try_from(len.eval_usize(tcx, param_env)).unwrap(), None, op),
55 // Checks if we have any variants, to avoid downcasting to a non-existing variant (when
56 // there are no variants `read_discriminant` successfully returns a non-existing variant
57 // index).
58 ty::Adt(def, _) if def.variants().is_empty() => throw_ub!(Unreachable),
59 ty::Adt(def, _) => {
60 let variant = ecx.read_discriminant(&op)?.1;
61 let down = ecx.operand_downcast(&op, variant)?;
62 (def.variant(variant).fields.len(), Some(variant), down)
63 }
64 ty::Tuple(substs) => (substs.len(), None, op),
65 _ => bug!("cannot destructure constant {:?}", val),
66 };
67
68 let fields = (0..field_count)
69 .map(|i| {
70 let field_op = ecx.operand_field(&down, i)?;
71 let val = op_to_const(&ecx, &field_op);
72 Ok(ty::Const::from_value(tcx, val, field_op.layout.ty))
73 })
74 .collect::<InterpResult<'tcx, Vec<_>>>()?;
75 let fields = tcx.arena.alloc_from_iter(fields);
76
77 Ok(mir::DestructuredConst { variant, fields })
78 }
79
80 #[instrument(skip(tcx), level = "debug")]
81 pub(crate) fn deref_const<'tcx>(
82 tcx: TyCtxt<'tcx>,
83 param_env: ty::ParamEnv<'tcx>,
84 val: ty::Const<'tcx>,
85 ) -> ty::Const<'tcx> {
86 trace!("deref_const: {:?}", val);
87 let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false);
88 let op = ecx.const_to_op(val, None).unwrap();
89 let mplace = ecx.deref_operand(&op).unwrap();
90 if let Some(alloc_id) = mplace.ptr.provenance {
91 assert_eq!(
92 tcx.get_global_alloc(alloc_id).unwrap().unwrap_memory().inner().mutability,
93 Mutability::Not,
94 "deref_const cannot be used with mutable allocations as \
95 that could allow pattern matching to observe mutable statics",
96 );
97 }
98
99 let ty = match mplace.meta {
100 MemPlaceMeta::None => mplace.layout.ty,
101 MemPlaceMeta::Poison => bug!("poison metadata in `deref_const`: {:#?}", mplace),
102 // In case of unsized types, figure out the real type behind.
103 MemPlaceMeta::Meta(scalar) => match mplace.layout.ty.kind() {
104 ty::Str => bug!("there's no sized equivalent of a `str`"),
105 ty::Slice(elem_ty) => tcx.mk_array(*elem_ty, scalar.to_machine_usize(&tcx).unwrap()),
106 _ => bug!(
107 "type {} should not have metadata, but had {:?}",
108 mplace.layout.ty,
109 mplace.meta
110 ),
111 },
112 };
113
114 tcx.mk_const(ty::ConstS { val: ty::ConstKind::Value(op_to_const(&ecx, &mplace.into())), ty })
115 }