]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/visitor.rs
Rollup merge of #66045 - mzabaluev:unwrap-infallible, r=dtolnay
[rust.git] / src / librustc_mir / interpret / visitor.rs
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.
3
4 use rustc::mir::interpret::InterpResult;
5 use rustc::ty;
6 use rustc::ty::layout::{self, TyLayout, VariantIdx};
7
8 use super::{InterpCx, MPlaceTy, Machine, OpTy};
9
10 // A thing that we can project into, and that has a layout.
11 // This wouldn't have to depend on `Machine` but with the current type inference,
12 // that's just more convenient to work with (avoids repeating all the `Machine` bounds).
13 pub trait Value<'mir, 'tcx, M: Machine<'mir, 'tcx>>: Copy {
14     /// Gets this value's layout.
15     fn layout(&self) -> TyLayout<'tcx>;
16
17     /// Makes this into an `OpTy`.
18     fn to_op(self, ecx: &InterpCx<'mir, 'tcx, M>) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>>;
19
20     /// Creates this from an `MPlaceTy`.
21     fn from_mem_place(mplace: MPlaceTy<'tcx, M::PointerTag>) -> Self;
22
23     /// Projects to the given enum variant.
24     fn project_downcast(
25         self,
26         ecx: &InterpCx<'mir, 'tcx, M>,
27         variant: VariantIdx,
28     ) -> InterpResult<'tcx, Self>;
29
30     /// Projects to the n-th field.
31     fn project_field(self, ecx: &InterpCx<'mir, 'tcx, M>, field: u64) -> InterpResult<'tcx, Self>;
32 }
33
34 // Operands and memory-places are both values.
35 // Places in general are not due to `place_field` having to do `force_allocation`.
36 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Value<'mir, 'tcx, M> for OpTy<'tcx, M::PointerTag> {
37     #[inline(always)]
38     fn layout(&self) -> TyLayout<'tcx> {
39         self.layout
40     }
41
42     #[inline(always)]
43     fn to_op(
44         self,
45         _ecx: &InterpCx<'mir, 'tcx, M>,
46     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
47         Ok(self)
48     }
49
50     #[inline(always)]
51     fn from_mem_place(mplace: MPlaceTy<'tcx, M::PointerTag>) -> Self {
52         mplace.into()
53     }
54
55     #[inline(always)]
56     fn project_downcast(
57         self,
58         ecx: &InterpCx<'mir, 'tcx, M>,
59         variant: VariantIdx,
60     ) -> InterpResult<'tcx, Self> {
61         ecx.operand_downcast(self, variant)
62     }
63
64     #[inline(always)]
65     fn project_field(self, ecx: &InterpCx<'mir, 'tcx, M>, field: u64) -> InterpResult<'tcx, Self> {
66         ecx.operand_field(self, field)
67     }
68 }
69
70 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Value<'mir, 'tcx, M> for MPlaceTy<'tcx, M::PointerTag> {
71     #[inline(always)]
72     fn layout(&self) -> TyLayout<'tcx> {
73         self.layout
74     }
75
76     #[inline(always)]
77     fn to_op(
78         self,
79         _ecx: &InterpCx<'mir, 'tcx, M>,
80     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
81         Ok(self.into())
82     }
83
84     #[inline(always)]
85     fn from_mem_place(mplace: MPlaceTy<'tcx, M::PointerTag>) -> Self {
86         mplace
87     }
88
89     #[inline(always)]
90     fn project_downcast(
91         self,
92         ecx: &InterpCx<'mir, 'tcx, M>,
93         variant: VariantIdx,
94     ) -> InterpResult<'tcx, Self> {
95         ecx.mplace_downcast(self, variant)
96     }
97
98     #[inline(always)]
99     fn project_field(self, ecx: &InterpCx<'mir, 'tcx, M>, field: u64) -> InterpResult<'tcx, Self> {
100         ecx.mplace_field(self, field)
101     }
102 }
103
104 macro_rules! make_value_visitor {
105     ($visitor_trait_name:ident, $($mutability:ident)?) => {
106         // How to traverse a value and what to do when we are at the leaves.
107         pub trait $visitor_trait_name<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>>: Sized {
108             type V: Value<'mir, 'tcx, M>;
109
110             /// The visitor must have an `InterpCx` in it.
111             fn ecx(&$($mutability)? self)
112                 -> &$($mutability)? InterpCx<'mir, 'tcx, M>;
113
114             // Recursive actions, ready to be overloaded.
115             /// Visits the given value, dispatching as appropriate to more specialized visitors.
116             #[inline(always)]
117             fn visit_value(&mut self, v: Self::V) -> InterpResult<'tcx>
118             {
119                 self.walk_value(v)
120             }
121             /// Visits the given value as a union. No automatic recursion can happen here.
122             #[inline(always)]
123             fn visit_union(&mut self, _v: Self::V) -> InterpResult<'tcx>
124             {
125                 Ok(())
126             }
127             /// Visits this value as an aggregate, you are getting an iterator yielding
128             /// all the fields (still in an `InterpResult`, you have to do error handling yourself).
129             /// Recurses into the fields.
130             #[inline(always)]
131             fn visit_aggregate(
132                 &mut self,
133                 v: Self::V,
134                 fields: impl Iterator<Item=InterpResult<'tcx, Self::V>>,
135             ) -> InterpResult<'tcx> {
136                 self.walk_aggregate(v, fields)
137             }
138
139             /// Called each time we recurse down to a field of a "product-like" aggregate
140             /// (structs, tuples, arrays and the like, but not enums), passing in old (outer)
141             /// and new (inner) value.
142             /// This gives the visitor the chance to track the stack of nested fields that
143             /// we are descending through.
144             #[inline(always)]
145             fn visit_field(
146                 &mut self,
147                 _old_val: Self::V,
148                 _field: usize,
149                 new_val: Self::V,
150             ) -> InterpResult<'tcx> {
151                 self.visit_value(new_val)
152             }
153
154             /// Called when recursing into an enum variant.
155             #[inline(always)]
156             fn visit_variant(
157                 &mut self,
158                 _old_val: Self::V,
159                 _variant: VariantIdx,
160                 new_val: Self::V,
161             ) -> InterpResult<'tcx> {
162                 self.visit_value(new_val)
163             }
164
165             /// Called whenever we reach a value with uninhabited layout.
166             /// Recursing to fields will *always* continue after this!  This is not meant to control
167             /// whether and how we descend recursively/ into the scalar's fields if there are any,
168             /// it is meant to provide the chance for additional checks when a value of uninhabited
169             /// layout is detected.
170             #[inline(always)]
171             fn visit_uninhabited(&mut self) -> InterpResult<'tcx>
172             { Ok(()) }
173             /// Called whenever we reach a value with scalar layout.
174             /// We do NOT provide a `ScalarMaybeUndef` here to avoid accessing memory if the
175             /// visitor is not even interested in scalars.
176             /// Recursing to fields will *always* continue after this!  This is not meant to control
177             /// whether and how we descend recursively/ into the scalar's fields if there are any,
178             /// it is meant to provide the chance for additional checks when a value of scalar
179             /// layout is detected.
180             #[inline(always)]
181             fn visit_scalar(&mut self, _v: Self::V, _layout: &layout::Scalar) -> InterpResult<'tcx>
182             { Ok(()) }
183
184             /// Called whenever we reach a value of primitive type. There can be no recursion
185             /// below such a value. This is the leaf function.
186             /// We do *not* provide an `ImmTy` here because some implementations might want
187             /// to write to the place this primitive lives in.
188             #[inline(always)]
189             fn visit_primitive(&mut self, _v: Self::V) -> InterpResult<'tcx>
190             { Ok(()) }
191
192             // Default recursors. Not meant to be overloaded.
193             fn walk_aggregate(
194                 &mut self,
195                 v: Self::V,
196                 fields: impl Iterator<Item=InterpResult<'tcx, Self::V>>,
197             ) -> InterpResult<'tcx> {
198                 // Now iterate over it.
199                 for (idx, field_val) in fields.enumerate() {
200                     self.visit_field(v, idx, field_val?)?;
201                 }
202                 Ok(())
203             }
204             fn walk_value(&mut self, v: Self::V) -> InterpResult<'tcx>
205             {
206                 trace!("walk_value: type: {}", v.layout().ty);
207                 // If this is a multi-variant layout, we have to find the right one and proceed with
208                 // that.
209                 match v.layout().variants {
210                     layout::Variants::Multiple { .. } => {
211                         let op = v.to_op(self.ecx())?;
212                         let idx = self.ecx().read_discriminant(op)?.1;
213                         let inner = v.project_downcast(self.ecx(), idx)?;
214                         trace!("walk_value: variant layout: {:#?}", inner.layout());
215                         // recurse with the inner type
216                         return self.visit_variant(v, idx, inner);
217                     }
218                     layout::Variants::Single { .. } => {}
219                 }
220
221                 // Even for single variants, we might be able to get a more refined type:
222                 // If it is a trait object, switch to the actual type that was used to create it.
223                 match v.layout().ty.kind {
224                     ty::Dynamic(..) => {
225                         // immediate trait objects are not a thing
226                         let dest = v.to_op(self.ecx())?.assert_mem_place(self.ecx());
227                         let inner = self.ecx().unpack_dyn_trait(dest)?.1;
228                         trace!("walk_value: dyn object layout: {:#?}", inner.layout);
229                         // recurse with the inner type
230                         return self.visit_field(v, 0, Value::from_mem_place(inner));
231                     },
232                     ty::Generator(..) => {
233                         // FIXME: Generator layout is lying: it claims a whole bunch of fields exist
234                         // when really many of them can be uninitialized.
235                         // Just treat them as a union for now, until hopefully the layout
236                         // computation is fixed.
237                         return self.visit_union(v);
238                     }
239                     _ => {},
240                 };
241
242                 // If this is a scalar, visit it as such.
243                 // Things can be aggregates and have scalar layout at the same time, and that
244                 // is very relevant for `NonNull` and similar structs: We need to visit them
245                 // at their scalar layout *before* descending into their fields.
246                 // FIXME: We could avoid some redundant checks here. For newtypes wrapping
247                 // scalars, we do the same check on every "level" (e.g., first we check
248                 // MyNewtype and then the scalar in there).
249                 match v.layout().abi {
250                     layout::Abi::Uninhabited => {
251                         self.visit_uninhabited()?;
252                     }
253                     layout::Abi::Scalar(ref layout) => {
254                         self.visit_scalar(v, layout)?;
255                     }
256                     // FIXME: Should we do something for ScalarPair? Vector?
257                     _ => {}
258                 }
259
260                 // Check primitive types.  We do this after checking the scalar layout,
261                 // just to have that done as well.  Primitives can have varying layout,
262                 // so we check them separately and before aggregate handling.
263                 // It is CRITICAL that we get this check right, or we might be
264                 // validating the wrong thing!
265                 let primitive = match v.layout().fields {
266                     // Primitives appear as Union with 0 fields - except for Boxes and fat pointers.
267                     layout::FieldPlacement::Union(0) => true,
268                     _ => v.layout().ty.builtin_deref(true).is_some(),
269                 };
270                 if primitive {
271                     return self.visit_primitive(v);
272                 }
273
274                 // Proceed into the fields.
275                 match v.layout().fields {
276                     layout::FieldPlacement::Union(fields) => {
277                         // Empty unions are not accepted by rustc. That's great, it means we can
278                         // use that as an unambiguous signal for detecting primitives.  Make sure
279                         // we did not miss any primitive.
280                         assert!(fields > 0);
281                         self.visit_union(v)
282                     },
283                     layout::FieldPlacement::Arbitrary { ref offsets, .. } => {
284                         // FIXME: We collect in a vec because otherwise there are lifetime
285                         // errors: Projecting to a field needs access to `ecx`.
286                         let fields: Vec<InterpResult<'tcx, Self::V>> =
287                             (0..offsets.len()).map(|i| {
288                                 v.project_field(self.ecx(), i as u64)
289                             })
290                             .collect();
291                         self.visit_aggregate(v, fields.into_iter())
292                     },
293                     layout::FieldPlacement::Array { .. } => {
294                         // Let's get an mplace first.
295                         let mplace = v.to_op(self.ecx())?.assert_mem_place(self.ecx());
296                         // Now we can go over all the fields.
297                         let iter = self.ecx().mplace_array_fields(mplace)?
298                             .map(|f| f.and_then(|f| {
299                                 Ok(Value::from_mem_place(f))
300                             }));
301                         self.visit_aggregate(v, iter)
302                     }
303                 }
304             }
305         }
306     }
307 }
308
309 make_value_visitor!(ValueVisitor,);
310 make_value_visitor!(MutValueVisitor, mut);