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::ty::{self, TyCtxt};
7 use rustc_middle::{
8     mir::{self, interpret::ConstAlloc},
9     ty::ScalarInt,
10 };
11 use rustc_span::{source_map::DUMMY_SP, symbol::Symbol};
12 
13 use crate::interpret::{
14     intern_const_alloc_recursive, ConstValue, InternKind, InterpCx, MPlaceTy, MemPlaceMeta, Scalar,
15 };
16 
17 mod error;
18 mod eval_queries;
19 mod fn_queries;
20 mod machine;
21 
22 pub use error::*;
23 pub use eval_queries::*;
24 pub use fn_queries::*;
25 pub use machine::*;
26 
const_caller_location( tcx: TyCtxt<'tcx>, (file, line, col): (Symbol, u32, u32), ) -> ConstValue<'tcx>27 pub(crate) fn const_caller_location(
28     tcx: TyCtxt<'tcx>,
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);
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_pointer(loc_place.ptr.into_pointer_or_addr().unwrap(), &tcx))
39 }
40 
41 /// Convert an evaluated constant to a type level constant
const_to_valtree<'tcx>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, raw: ConstAlloc<'tcx>, ) -> Option<ty::ValTree<'tcx>>42 pub(crate) fn const_to_valtree<'tcx>(
43     tcx: TyCtxt<'tcx>,
44     param_env: ty::ParamEnv<'tcx>,
45     raw: ConstAlloc<'tcx>,
46 ) -> Option<ty::ValTree<'tcx>> {
47     let ecx = mk_eval_cx(
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.
51         false,
52     );
53     let place = ecx.raw_const_to_mplace(raw).unwrap();
54     const_to_valtree_inner(&ecx, &place)
55 }
56 
const_to_valtree_inner<'tcx>( ecx: &CompileTimeEvalContext<'tcx, 'tcx>, place: &MPlaceTy<'tcx>, ) -> Option<ty::ValTree<'tcx>>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(),
64             None => *place,
65         };
66         let variant =
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)
71         });
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<_>>>()?),
77         ))
78     };
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()))
85         }
86 
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"),
93 
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,
99 
100         ty::Slice(_) | ty::Str => {
101             unimplemented!("need to find the backing data of the slice/str and recurse on that")
102         }
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),
105 
106         ty::Adt(def, _) => {
107             if def.variants.is_empty() {
108                 bug!("uninhabited types should have errored and never gotten converted to valtree")
109             }
110 
111             let variant = ecx.read_discriminant(&place.into()).unwrap().1;
112 
113             branches(def.variants[variant].fields.len(), def.is_enum().then_some(variant))
114         }
115 
116         ty::Never
117         | ty::Error(_)
118         | ty::Foreign(..)
119         | ty::Infer(ty::FreshIntTy(_))
120         | ty::Infer(ty::FreshFloatTy(_))
121         | ty::Projection(..)
122         | ty::Param(_)
123         | ty::Bound(..)
124         | ty::Placeholder(..)
125         // FIXME(oli-obk): we could look behind opaque types
126         | ty::Opaque(..)
127         | ty::Infer(_)
128         // FIXME(oli-obk): we can probably encode closures just like structs
129         | ty::Closure(..)
130         | ty::Generator(..)
131         | ty::GeneratorWitness(..) => None,
132     }
133 }
134 
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.
destructure_const<'tcx>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, val: &'tcx ty::Const<'tcx>, ) -> mir::DestructuredConst<'tcx>139 pub(crate) fn destructure_const<'tcx>(
140     tcx: TyCtxt<'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();
147 
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: &[] };
153         }
154         ty::Adt(def, _) => {
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)
158         }
159         ty::Tuple(substs) => (substs.len(), None, op),
160         _ => bug!("cannot destructure constant {:?}", val),
161     };
162 
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)
167     });
168     let fields = tcx.arena.alloc_from_iter(fields_iter);
169 
170     mir::DestructuredConst { variant, fields }
171 }
172 
deref_const<'tcx>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, val: &'tcx ty::Const<'tcx>, ) -> &'tcx ty::Const<'tcx>173 pub(crate) fn deref_const<'tcx>(
174     tcx: TyCtxt<'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 Some(alloc_id) = mplace.ptr.provenance {
183         assert_eq!(
184             tcx.get_global_alloc(alloc_id).unwrap().unwrap_memory().mutability,
185             Mutability::Not,
186             "deref_const cannot be used with mutable allocations as \
187             that could allow pattern matching to observe mutable statics",
188         );
189     }
190 
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()),
198             _ => bug!(
199                 "type {} should not have metadata, but had {:?}",
200                 mplace.layout.ty,
201                 mplace.meta
202             ),
203         },
204     };
205 
206     tcx.mk_const(ty::Const { val: ty::ConstKind::Value(op_to_const(&ecx, &mplace.into())), ty })
207 }
208