1 // Not in interpret to make sure we do not use private implementation details
3 use std::convert::TryFrom;
5 use rustc_hir::Mutability;
6 use rustc_middle::ty::{self, TyCtxt};
8 mir::{self, interpret::ConstAlloc},
11 use rustc_span::{source_map::DUMMY_SP, symbol::Symbol};
13 use crate::interpret::{
14 intern_const_alloc_recursive, ConstValue, InternKind, InterpCx, MPlaceTy, MemPlaceMeta, Scalar,
23 pub use eval_queries::*;
24 pub use fn_queries::*;
27 pub(crate) fn const_caller_location(
29 (file, line, col): (Symbol, u32, u32),
30 ) -> ConstValue<'tcx> {
31 trace!("const_caller_location: {}:{}:{}", file, line, col);
32 let mut ecx = mk_eval_cx(tcx, DUMMY_SP, ty::ParamEnv::reveal_all(), false);
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")
38 ConstValue::Scalar(loc_place.ptr)
41 /// Convert an evaluated constant to a type level constant
42 pub(crate) fn const_to_valtree<'tcx>(
44 param_env: ty::ParamEnv<'tcx>,
45 raw: ConstAlloc<'tcx>,
46 ) -> Option<ty::ValTree<'tcx>> {
48 tcx, DUMMY_SP, param_env,
49 // It is absolutely crucial for soundness that
50 // we do not read from static items or other mutable memory.
53 let place = ecx.raw_const_to_mplace(raw).unwrap();
54 const_to_valtree_inner(&ecx, &place)
57 fn const_to_valtree_inner<'tcx>(
58 ecx: &CompileTimeEvalContext<'tcx, 'tcx>,
59 place: &MPlaceTy<'tcx>,
60 ) -> Option<ty::ValTree<'tcx>> {
61 let branches = |n, variant| {
62 let place = match variant {
63 Some(variant) => ecx.mplace_downcast(&place, variant).unwrap(),
67 variant.map(|variant| Some(ty::ValTree::Leaf(ScalarInt::from(variant.as_u32()))));
68 let fields = (0..n).map(|i| {
69 let field = ecx.mplace_field(&place, i).unwrap();
70 const_to_valtree_inner(ecx, &field)
72 // For enums, we preped their variant index before the variant's fields so we can figure out
73 // the variant again when just seeing a valtree.
74 let branches = variant.into_iter().chain(fields);
75 Some(ty::ValTree::Branch(
76 ecx.tcx.arena.alloc_from_iter(branches.collect::<Option<Vec<_>>>()?),
79 match place.layout.ty.kind() {
80 ty::FnDef(..) => Some(ty::ValTree::zst()),
81 ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Char => {
82 let val = ecx.read_immediate(&place.into()).unwrap();
83 let val = val.to_scalar().unwrap();
84 Some(ty::ValTree::Leaf(val.assert_int()))
87 // Raw pointers are not allowed in type level constants, as we cannot properly test them for
88 // equality at compile-time (see `ptr_guaranteed_eq`/`_ne`).
89 // Technically we could allow function pointers (represented as `ty::Instance`), but this is not guaranteed to
90 // agree with runtime equality tests.
91 ty::FnPtr(_) | ty::RawPtr(_) => None,
92 ty::Ref(..) => unimplemented!("need to use deref_const"),
94 // Trait objects are not allowed in type level constants, as we have no concept for
95 // resolving their backing type, even if we can do that at const eval time. We may
96 // hypothetically be able to allow `dyn StructuralEq` trait objects in the future,
97 // but it is unclear if this is useful.
98 ty::Dynamic(..) => None,
100 ty::Slice(_) | ty::Str => {
101 unimplemented!("need to find the backing data of the slice/str and recurse on that")
103 ty::Tuple(substs) => branches(substs.len(), None),
104 ty::Array(_, len) => branches(usize::try_from(len.eval_usize(ecx.tcx.tcx, ecx.param_env)).unwrap(), None),
107 if def.variants.is_empty() {
108 bug!("uninhabited types should have errored and never gotten converted to valtree")
111 let variant = ecx.read_discriminant(&place.into()).unwrap().1;
113 branches(def.variants[variant].fields.len(), def.is_enum().then_some(variant))
119 | ty::Infer(ty::FreshIntTy(_))
120 | ty::Infer(ty::FreshFloatTy(_))
124 | ty::Placeholder(..)
125 // FIXME(oli-obk): we could look behind opaque types
128 // FIXME(oli-obk): we can probably encode closures just like structs
131 | ty::GeneratorWitness(..) => None,
135 /// This function uses `unwrap` copiously, because an already validated constant
136 /// must have valid fields and can thus never fail outside of compiler bugs. However, it is
137 /// invoked from the pretty printer, where it can receive enums with no variants and e.g.
138 /// `read_discriminant` needs to be able to handle that.
139 pub(crate) fn destructure_const<'tcx>(
141 param_env: ty::ParamEnv<'tcx>,
142 val: &'tcx ty::Const<'tcx>,
143 ) -> mir::DestructuredConst<'tcx> {
144 trace!("destructure_const: {:?}", val);
145 let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false);
146 let op = ecx.const_to_op(val, None).unwrap();
148 // We go to `usize` as we cannot allocate anything bigger anyway.
149 let (field_count, variant, down) = match val.ty.kind() {
150 ty::Array(_, len) => (usize::try_from(len.eval_usize(tcx, param_env)).unwrap(), None, op),
151 ty::Adt(def, _) if def.variants.is_empty() => {
152 return mir::DestructuredConst { variant: None, fields: &[] };
155 let variant = ecx.read_discriminant(&op).unwrap().1;
156 let down = ecx.operand_downcast(&op, variant).unwrap();
157 (def.variants[variant].fields.len(), Some(variant), down)
159 ty::Tuple(substs) => (substs.len(), None, op),
160 _ => bug!("cannot destructure constant {:?}", val),
163 let fields_iter = (0..field_count).map(|i| {
164 let field_op = ecx.operand_field(&down, i).unwrap();
165 let val = op_to_const(&ecx, &field_op);
166 ty::Const::from_value(tcx, val, field_op.layout.ty)
168 let fields = tcx.arena.alloc_from_iter(fields_iter);
170 mir::DestructuredConst { variant, fields }
173 pub(crate) fn deref_const<'tcx>(
175 param_env: ty::ParamEnv<'tcx>,
176 val: &'tcx ty::Const<'tcx>,
177 ) -> &'tcx ty::Const<'tcx> {
178 trace!("deref_const: {:?}", val);
179 let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false);
180 let op = ecx.const_to_op(val, None).unwrap();
181 let mplace = ecx.deref_operand(&op).unwrap();
182 if let Scalar::Ptr(ptr) = mplace.ptr {
184 tcx.get_global_alloc(ptr.alloc_id).unwrap().unwrap_memory().mutability,
186 "deref_const cannot be used with mutable allocations as \
187 that could allow pattern matching to observe mutable statics",
191 let ty = match mplace.meta {
192 MemPlaceMeta::None => mplace.layout.ty,
193 MemPlaceMeta::Poison => bug!("poison metadata in `deref_const`: {:#?}", mplace),
194 // In case of unsized types, figure out the real type behind.
195 MemPlaceMeta::Meta(scalar) => match mplace.layout.ty.kind() {
196 ty::Str => bug!("there's no sized equivalent of a `str`"),
197 ty::Slice(elem_ty) => tcx.mk_array(elem_ty, scalar.to_machine_usize(&tcx).unwrap()),
199 "type {} should not have metadata, but had {:?}",
206 tcx.mk_const(ty::Const { val: ty::ConstKind::Value(op_to_const(&ecx, &mplace.into())), ty })