rustc_const_eval/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
4use std::num::NonZero;
5
6use rustc_abi::{FieldIdx, FieldsShape, VariantIdx, Variants};
7use rustc_index::IndexVec;
8use rustc_middle::mir::interpret::InterpResult;
9use rustc_middle::ty::layout::LayoutOf;
10use rustc_middle::ty::{self, Ty};
11use tracing::trace;
12
13use super::{InterpCx, MPlaceTy, Machine, Projectable, interp_ok, throw_inval};
14
15/// How to traverse a value and what to do when we are at the leaves.
16pub trait ValueVisitor<'tcx, M: Machine<'tcx>>: Sized {
17 type V: Projectable<'tcx, M::Provenance> + From<MPlaceTy<'tcx, M::Provenance>>;
18
19 /// The visitor must have an `InterpCx` in it.
20 fn ecx(&self) -> &InterpCx<'tcx, M>;
21
22 /// `read_discriminant` can be hooked for better error messages.
23 #[inline(always)]
24 fn read_discriminant(&mut self, v: &Self::V) -> InterpResult<'tcx, VariantIdx> {
25 self.ecx().read_discriminant(&v.to_op(self.ecx())?)
26 }
27
28 /// This function provides the chance to reorder the order in which fields are visited for
29 /// `FieldsShape::Aggregate`.
30 ///
31 /// The default means we iterate in source declaration order; alternatively this can do some
32 /// work with `memory_index` to iterate in memory order.
33 #[inline(always)]
34 fn aggregate_field_iter(
35 memory_index: &IndexVec<FieldIdx, u32>,
36 ) -> impl Iterator<Item = FieldIdx> + 'static {
37 memory_index.indices()
38 }
39
40 // Recursive actions, ready to be overloaded.
41 /// Visits the given value, dispatching as appropriate to more specialized visitors.
42 #[inline(always)]
43 fn visit_value(&mut self, v: &Self::V) -> InterpResult<'tcx> {
44 self.walk_value(v)
45 }
46 /// Visits the given value as a union. No automatic recursion can happen here.
47 #[inline(always)]
48 fn visit_union(&mut self, _v: &Self::V, _fields: NonZero<usize>) -> InterpResult<'tcx> {
49 interp_ok(())
50 }
51 /// Visits the given value as the pointer of a `Box`. There is nothing to recurse into.
52 /// The type of `v` will be a raw pointer to `T`, but this is a field of `Box<T>` and the
53 /// pointee type is the actual `T`. `box_ty` provides the full type of the `Box` itself.
54 #[inline(always)]
55 fn visit_box(&mut self, _box_ty: Ty<'tcx>, _v: &Self::V) -> InterpResult<'tcx> {
56 interp_ok(())
57 }
58
59 /// Called each time we recurse down to a field of a "product-like" aggregate
60 /// (structs, tuples, arrays and the like, but not enums), passing in old (outer)
61 /// and new (inner) value.
62 /// This gives the visitor the chance to track the stack of nested fields that
63 /// we are descending through.
64 #[inline(always)]
65 fn visit_field(
66 &mut self,
67 _old_val: &Self::V,
68 _field: usize,
69 new_val: &Self::V,
70 ) -> InterpResult<'tcx> {
71 self.visit_value(new_val)
72 }
73 /// Called when recursing into an enum variant.
74 /// This gives the visitor the chance to track the stack of nested fields that
75 /// we are descending through.
76 #[inline(always)]
77 fn visit_variant(
78 &mut self,
79 _old_val: &Self::V,
80 _variant: VariantIdx,
81 new_val: &Self::V,
82 ) -> InterpResult<'tcx> {
83 self.visit_value(new_val)
84 }
85
86 /// Traversal logic; should not be overloaded.
87 fn walk_value(&mut self, v: &Self::V) -> InterpResult<'tcx> {
88 let ty = v.layout().ty;
89 trace!("walk_value: type: {ty}");
90
91 // Special treatment for special types, where the (static) layout is not sufficient.
92 match *ty.kind() {
93 // If it is a trait object, switch to the real type that was used to create it.
94 ty::Dynamic(data, _, ty::Dyn) => {
95 // Dyn types. This is unsized, and the actual dynamic type of the data is given by the
96 // vtable stored in the place metadata.
97 // unsized values are never immediate, so we can assert_mem_place
98 let op = v.to_op(self.ecx())?;
99 let dest = op.assert_mem_place();
100 let inner_mplace = self.ecx().unpack_dyn_trait(&dest, data)?;
101 trace!("walk_value: dyn object layout: {:#?}", inner_mplace.layout);
102 // recurse with the inner type
103 return self.visit_field(v, 0, &inner_mplace.into());
104 }
105 ty::Dynamic(data, _, ty::DynStar) => {
106 // DynStar types. Very different from a dyn type (but strangely part of the
107 // same variant in `TyKind`): These are pairs where the 2nd component is the
108 // vtable, and the first component is the data (which must be ptr-sized).
109
110 // First make sure the vtable can be read at its type.
111 // The type of this vtable is fake, it claims to be a reference to some actual memory but that isn't true.
112 // So we transmute it to a raw pointer.
113 let raw_ptr_ty = Ty::new_mut_ptr(*self.ecx().tcx, self.ecx().tcx.types.unit);
114 let raw_ptr_ty = self.ecx().layout_of(raw_ptr_ty)?;
115 let vtable_field = self
116 .ecx()
117 .project_field(v, FieldIdx::ONE)?
118 .transmute(raw_ptr_ty, self.ecx())?;
119 self.visit_field(v, 1, &vtable_field)?;
120
121 // Then unpack the first field, and continue.
122 let data = self.ecx().unpack_dyn_star(v, data)?;
123 return self.visit_field(v, 0, &data);
124 }
125 // Slices do not need special handling here: they have `Array` field
126 // placement with length 0, so we enter the `Array` case below which
127 // indirectly uses the metadata to determine the actual length.
128
129 // However, `Box`... let's talk about `Box`.
130 ty::Adt(def, ..) if def.is_box() => {
131 // `Box` is a hybrid primitive-library-defined type that one the one hand is
132 // a dereferenceable pointer, on the other hand has *basically arbitrary
133 // user-defined layout* since the user controls the 'allocator' field. So it
134 // cannot be treated like a normal pointer, since it does not fit into an
135 // `Immediate`. Yeah, it is quite terrible. But many visitors want to do
136 // something with "all boxed pointers", so we handle this mess for them.
137 //
138 // When we hit a `Box`, we do not do the usual field recursion; instead,
139 // we (a) call `visit_box` on the pointer value, and (b) recurse on the
140 // allocator field. We also assert tons of things to ensure we do not miss
141 // any other fields.
142
143 // `Box` has two fields: the pointer we care about, and the allocator.
144 assert_eq!(v.layout().fields.count(), 2, "`Box` must have exactly 2 fields");
145 let (unique_ptr, alloc) = (
146 self.ecx().project_field(v, FieldIdx::ZERO)?,
147 self.ecx().project_field(v, FieldIdx::ONE)?,
148 );
149 // Unfortunately there is some type junk in the way here: `unique_ptr` is a `Unique`...
150 // (which means another 2 fields, the second of which is a `PhantomData`)
151 assert_eq!(unique_ptr.layout().fields.count(), 2);
152 let (nonnull_ptr, phantom) = (
153 self.ecx().project_field(&unique_ptr, FieldIdx::ZERO)?,
154 self.ecx().project_field(&unique_ptr, FieldIdx::ONE)?,
155 );
156 assert!(
157 phantom.layout().ty.ty_adt_def().is_some_and(|adt| adt.is_phantom_data()),
158 "2nd field of `Unique` should be PhantomData but is {:?}",
159 phantom.layout().ty,
160 );
161 // ... that contains a `NonNull`... (gladly, only a single field here)
162 assert_eq!(nonnull_ptr.layout().fields.count(), 1);
163 let raw_ptr = self.ecx().project_field(&nonnull_ptr, FieldIdx::ZERO)?; // the actual raw ptr
164 // ... whose only field finally is a raw ptr we can dereference.
165 self.visit_box(ty, &raw_ptr)?;
166
167 // The second `Box` field is the allocator, which we recursively check for validity
168 // like in regular structs.
169 self.visit_field(v, 1, &alloc)?;
170
171 // We visited all parts of this one.
172 return interp_ok(());
173 }
174
175 // Non-normalized types should never show up here.
176 ty::Param(..)
177 | ty::Alias(..)
178 | ty::Bound(..)
179 | ty::Placeholder(..)
180 | ty::Infer(..)
181 | ty::Error(..) => throw_inval!(TooGeneric),
182
183 // The rest is handled below.
184 _ => {}
185 };
186
187 // Visit the fields of this value.
188 match &v.layout().fields {
189 FieldsShape::Primitive => {}
190 &FieldsShape::Union(fields) => {
191 self.visit_union(v, fields)?;
192 }
193 FieldsShape::Arbitrary { memory_index, .. } => {
194 for idx in Self::aggregate_field_iter(memory_index) {
195 let field = self.ecx().project_field(v, idx)?;
196 self.visit_field(v, idx.as_usize(), &field)?;
197 }
198 }
199 FieldsShape::Array { .. } => {
200 let mut iter = self.ecx().project_array_fields(v)?;
201 while let Some((idx, field)) = iter.next(self.ecx())? {
202 self.visit_field(v, idx.try_into().unwrap(), &field)?;
203 }
204 }
205 }
206
207 match v.layout().variants {
208 // If this is a multi-variant layout, find the right variant and proceed
209 // with *its* fields.
210 Variants::Multiple { .. } => {
211 let idx = self.read_discriminant(v)?;
212 // There are 3 cases where downcasts can turn a Scalar/ScalarPair into a different ABI which
213 // could be a problem for `ImmTy` (see layout_sanity_check):
214 // - variant.size == Size::ZERO: works fine because `ImmTy::offset` has a special case for
215 // zero-sized layouts.
216 // - variant.fields.count() == 0: works fine because `ImmTy::offset` has a special case for
217 // zero-field aggregates.
218 // - variant.abi.is_uninhabited(): triggers UB in `read_discriminant` so we never get here.
219 let inner = self.ecx().project_downcast(v, idx)?;
220 trace!("walk_value: variant layout: {:#?}", inner.layout());
221 // recurse with the inner type
222 self.visit_variant(v, idx, &inner)?;
223 }
224 // For single-variant layouts, we already did everything there is to do.
225 Variants::Single { .. } | Variants::Empty => {}
226 }
227
228 interp_ok(())
229 }
230}