1 //! Visitor for a run-time value with a given layout: Traverse enums, structs and other compound
2 //! types until we arrive at the leaves, with custom handling for primitive types.
4 use rustc::ty::layout::{self, TyLayout, VariantIdx};
6 use rustc::mir::interpret::{
11 Machine, InterpretCx, MPlaceTy, OpTy,
14 // A thing that we can project into, and that has a layout.
15 // This wouldn't have to depend on `Machine` but with the current type inference,
16 // that's just more convenient to work with (avoids repeating all the `Machine` bounds).
17 pub trait Value<'mir, 'tcx, M: Machine<'mir, 'tcx>>: Copy {
18 /// Gets this value's layout.
19 fn layout(&self) -> TyLayout<'tcx>;
21 /// Makes this into an `OpTy`.
24 ecx: &InterpretCx<'mir, 'tcx, M>,
25 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>>;
27 /// Creates this from an `MPlaceTy`.
28 fn from_mem_place(mplace: MPlaceTy<'tcx, M::PointerTag>) -> Self;
30 /// Projects to the given enum variant.
33 ecx: &InterpretCx<'mir, 'tcx, M>,
35 ) -> InterpResult<'tcx, Self>;
37 /// Projects to the n-th field.
40 ecx: &InterpretCx<'mir, 'tcx, M>,
42 ) -> InterpResult<'tcx, Self>;
45 // Operands and memory-places are both values.
46 // Places in general are not due to `place_field` having to do `force_allocation`.
47 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Value<'mir, 'tcx, M> for OpTy<'tcx, M::PointerTag> {
49 fn layout(&self) -> TyLayout<'tcx> {
56 _ecx: &InterpretCx<'mir, 'tcx, M>,
57 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
62 fn from_mem_place(mplace: MPlaceTy<'tcx, M::PointerTag>) -> Self {
69 ecx: &InterpretCx<'mir, 'tcx, M>,
71 ) -> InterpResult<'tcx, Self> {
72 ecx.operand_downcast(self, variant)
78 ecx: &InterpretCx<'mir, 'tcx, M>,
80 ) -> InterpResult<'tcx, Self> {
81 ecx.operand_field(self, field)
84 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Value<'mir, 'tcx, M> for MPlaceTy<'tcx, M::PointerTag> {
86 fn layout(&self) -> TyLayout<'tcx> {
93 _ecx: &InterpretCx<'mir, 'tcx, M>,
94 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
99 fn from_mem_place(mplace: MPlaceTy<'tcx, M::PointerTag>) -> Self {
106 ecx: &InterpretCx<'mir, 'tcx, M>,
108 ) -> InterpResult<'tcx, Self> {
109 ecx.mplace_downcast(self, variant)
115 ecx: &InterpretCx<'mir, 'tcx, M>,
117 ) -> InterpResult<'tcx, Self> {
118 ecx.mplace_field(self, field)
122 macro_rules! make_value_visitor {
123 ($visitor_trait_name:ident, $($mutability:ident)?) => {
124 // How to traverse a value and what to do when we are at the leaves.
125 pub trait $visitor_trait_name<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>>: Sized {
126 type V: Value<'mir, 'tcx, M>;
128 /// The visitor must have an `InterpretCx` in it.
129 fn ecx(&$($mutability)? self)
130 -> &$($mutability)? InterpretCx<'mir, 'tcx, M>;
132 // Recursive actions, ready to be overloaded.
133 /// Visits the given value, dispatching as appropriate to more specialized visitors.
135 fn visit_value(&mut self, v: Self::V) -> InterpResult<'tcx>
139 /// Visits the given value as a union. No automatic recursion can happen here.
141 fn visit_union(&mut self, _v: Self::V) -> InterpResult<'tcx>
145 /// Visits this value as an aggregate, you are getting an iterator yielding
146 /// all the fields (still in an `InterpResult`, you have to do error handling yourself).
147 /// Recurses into the fields.
152 fields: impl Iterator<Item=InterpResult<'tcx, Self::V>>,
153 ) -> InterpResult<'tcx> {
154 self.walk_aggregate(v, fields)
157 /// Called each time we recurse down to a field of a "product-like" aggregate
158 /// (structs, tuples, arrays and the like, but not enums), passing in old (outer)
159 /// and new (inner) value.
160 /// This gives the visitor the chance to track the stack of nested fields that
161 /// we are descending through.
168 ) -> InterpResult<'tcx> {
169 self.visit_value(new_val)
172 /// Called when recursing into an enum variant.
177 _variant: VariantIdx,
179 ) -> InterpResult<'tcx> {
180 self.visit_value(new_val)
183 /// Called whenever we reach a value with uninhabited layout.
184 /// Recursing to fields will *always* continue after this! This is not meant to control
185 /// whether and how we descend recursively/ into the scalar's fields if there are any,
186 /// it is meant to provide the chance for additional checks when a value of uninhabited
187 /// layout is detected.
189 fn visit_uninhabited(&mut self) -> InterpResult<'tcx>
191 /// Called whenever we reach a value with scalar layout.
192 /// We do NOT provide a `ScalarMaybeUndef` here to avoid accessing memory if the
193 /// visitor is not even interested in scalars.
194 /// Recursing to fields will *always* continue after this! This is not meant to control
195 /// whether and how we descend recursively/ into the scalar's fields if there are any,
196 /// it is meant to provide the chance for additional checks when a value of scalar
197 /// layout is detected.
199 fn visit_scalar(&mut self, _v: Self::V, _layout: &layout::Scalar) -> InterpResult<'tcx>
202 /// Called whenever we reach a value of primitive type. There can be no recursion
203 /// below such a value. This is the leaf function.
204 /// We do *not* provide an `ImmTy` here because some implementations might want
205 /// to write to the place this primitive lives in.
207 fn visit_primitive(&mut self, _v: Self::V) -> InterpResult<'tcx>
210 // Default recursors. Not meant to be overloaded.
214 fields: impl Iterator<Item=InterpResult<'tcx, Self::V>>,
215 ) -> InterpResult<'tcx> {
216 // Now iterate over it.
217 for (idx, field_val) in fields.enumerate() {
218 self.visit_field(v, idx, field_val?)?;
222 fn walk_value(&mut self, v: Self::V) -> InterpResult<'tcx>
224 trace!("walk_value: type: {}", v.layout().ty);
225 // If this is a multi-variant layout, we have to find the right one and proceed with
227 match v.layout().variants {
228 layout::Variants::Multiple { .. } => {
229 let op = v.to_op(self.ecx())?;
230 let idx = self.ecx().read_discriminant(op)?.1;
231 let inner = v.project_downcast(self.ecx(), idx)?;
232 trace!("walk_value: variant layout: {:#?}", inner.layout());
233 // recurse with the inner type
234 return self.visit_variant(v, idx, inner);
236 layout::Variants::Single { .. } => {}
239 // Even for single variants, we might be able to get a more refined type:
240 // If it is a trait object, switch to the actual type that was used to create it.
241 match v.layout().ty.sty {
243 // immediate trait objects are not a thing
244 let dest = v.to_op(self.ecx())?.to_mem_place();
245 let inner = self.ecx().unpack_dyn_trait(dest)?.1;
246 trace!("walk_value: dyn object layout: {:#?}", inner.layout);
247 // recurse with the inner type
248 return self.visit_field(v, 0, Value::from_mem_place(inner));
250 ty::Generator(..) => {
251 // FIXME: Generator layout is lying: it claims a whole bunch of fields exist
252 // when really many of them can be uninitialized.
253 // Just treat them as a union for now, until hopefully the layout
254 // computation is fixed.
255 return self.visit_union(v);
260 // If this is a scalar, visit it as such.
261 // Things can be aggregates and have scalar layout at the same time, and that
262 // is very relevant for `NonNull` and similar structs: We need to visit them
263 // at their scalar layout *before* descending into their fields.
264 // FIXME: We could avoid some redundant checks here. For newtypes wrapping
265 // scalars, we do the same check on every "level" (e.g., first we check
266 // MyNewtype and then the scalar in there).
267 match v.layout().abi {
268 layout::Abi::Uninhabited => {
269 self.visit_uninhabited()?;
271 layout::Abi::Scalar(ref layout) => {
272 self.visit_scalar(v, layout)?;
274 // FIXME: Should we do something for ScalarPair? Vector?
278 // Check primitive types. We do this after checking the scalar layout,
279 // just to have that done as well. Primitives can have varying layout,
280 // so we check them separately and before aggregate handling.
281 // It is CRITICAL that we get this check right, or we might be
282 // validating the wrong thing!
283 let primitive = match v.layout().fields {
284 // Primitives appear as Union with 0 fields - except for Boxes and fat pointers.
285 layout::FieldPlacement::Union(0) => true,
286 _ => v.layout().ty.builtin_deref(true).is_some(),
289 return self.visit_primitive(v);
292 // Proceed into the fields.
293 match v.layout().fields {
294 layout::FieldPlacement::Union(fields) => {
295 // Empty unions are not accepted by rustc. That's great, it means we can
296 // use that as an unambiguous signal for detecting primitives. Make sure
297 // we did not miss any primitive.
301 layout::FieldPlacement::Arbitrary { ref offsets, .. } => {
302 // FIXME: We collect in a vec because otherwise there are lifetime
303 // errors: Projecting to a field needs access to `ecx`.
304 let fields: Vec<InterpResult<'tcx, Self::V>> =
305 (0..offsets.len()).map(|i| {
306 v.project_field(self.ecx(), i as u64)
309 self.visit_aggregate(v, fields.into_iter())
311 layout::FieldPlacement::Array { .. } => {
312 // Let's get an mplace first.
313 let mplace = if v.layout().is_zst() {
314 // it's a ZST, the memory content cannot matter
315 MPlaceTy::dangling(v.layout(), self.ecx())
317 // non-ZST array/slice/str cannot be immediate
318 v.to_op(self.ecx())?.to_mem_place()
320 // Now we can go over all the fields.
321 let iter = self.ecx().mplace_array_fields(mplace)?
322 .map(|f| f.and_then(|f| {
323 Ok(Value::from_mem_place(f))
325 self.visit_aggregate(v, iter)
333 make_value_visitor!(ValueVisitor,);
334 make_value_visitor!(MutValueVisitor,mut);