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 =
116 self.ecx().project_field(v, 1)?.transmute(raw_ptr_ty, self.ecx())?;
117 self.visit_field(v, 1, &vtable_field)?;
118
119 // Then unpack the first field, and continue.
120 let data = self.ecx().unpack_dyn_star(v, data)?;
121 return self.visit_field(v, 0, &data);
122 }
123 // Slices do not need special handling here: they have `Array` field
124 // placement with length 0, so we enter the `Array` case below which
125 // indirectly uses the metadata to determine the actual length.
126
127 // However, `Box`... let's talk about `Box`.
128 ty::Adt(def, ..) if def.is_box() => {
129 // `Box` is a hybrid primitive-library-defined type that one the one hand is
130 // a dereferenceable pointer, on the other hand has *basically arbitrary
131 // user-defined layout* since the user controls the 'allocator' field. So it
132 // cannot be treated like a normal pointer, since it does not fit into an
133 // `Immediate`. Yeah, it is quite terrible. But many visitors want to do
134 // something with "all boxed pointers", so we handle this mess for them.
135 //
136 // When we hit a `Box`, we do not do the usual field recursion; instead,
137 // we (a) call `visit_box` on the pointer value, and (b) recurse on the
138 // allocator field. We also assert tons of things to ensure we do not miss
139 // any other fields.
140
141 // `Box` has two fields: the pointer we care about, and the allocator.
142 assert_eq!(v.layout().fields.count(), 2, "`Box` must have exactly 2 fields");
143 let (unique_ptr, alloc) =
144 (self.ecx().project_field(v, 0)?, self.ecx().project_field(v, 1)?);
145 // Unfortunately there is some type junk in the way here: `unique_ptr` is a `Unique`...
146 // (which means another 2 fields, the second of which is a `PhantomData`)
147 assert_eq!(unique_ptr.layout().fields.count(), 2);
148 let (nonnull_ptr, phantom) = (
149 self.ecx().project_field(&unique_ptr, 0)?,
150 self.ecx().project_field(&unique_ptr, 1)?,
151 );
152 assert!(
153 phantom.layout().ty.ty_adt_def().is_some_and(|adt| adt.is_phantom_data()),
154 "2nd field of `Unique` should be PhantomData but is {:?}",
155 phantom.layout().ty,
156 );
157 // ... that contains a `NonNull`... (gladly, only a single field here)
158 assert_eq!(nonnull_ptr.layout().fields.count(), 1);
159 let raw_ptr = self.ecx().project_field(&nonnull_ptr, 0)?; // the actual raw ptr
160 // ... whose only field finally is a raw ptr we can dereference.
161 self.visit_box(ty, &raw_ptr)?;
162
163 // The second `Box` field is the allocator, which we recursively check for validity
164 // like in regular structs.
165 self.visit_field(v, 1, &alloc)?;
166
167 // We visited all parts of this one.
168 return interp_ok(());
169 }
170
171 // Non-normalized types should never show up here.
172 ty::Param(..)
173 | ty::Alias(..)
174 | ty::Bound(..)
175 | ty::Placeholder(..)
176 | ty::Infer(..)
177 | ty::Error(..) => throw_inval!(TooGeneric),
178
179 // The rest is handled below.
180 _ => {}
181 };
182
183 // Visit the fields of this value.
184 match &v.layout().fields {
185 FieldsShape::Primitive => {}
186 &FieldsShape::Union(fields) => {
187 self.visit_union(v, fields)?;
188 }
189 FieldsShape::Arbitrary { memory_index, .. } => {
190 for idx in Self::aggregate_field_iter(memory_index) {
191 let idx = idx.as_usize();
192 let field = self.ecx().project_field(v, idx)?;
193 self.visit_field(v, idx, &field)?;
194 }
195 }
196 FieldsShape::Array { .. } => {
197 let mut iter = self.ecx().project_array_fields(v)?;
198 while let Some((idx, field)) = iter.next(self.ecx())? {
199 self.visit_field(v, idx.try_into().unwrap(), &field)?;
200 }
201 }
202 }
203
204 match v.layout().variants {
205 // If this is a multi-variant layout, find the right variant and proceed
206 // with *its* fields.
207 Variants::Multiple { .. } => {
208 let idx = self.read_discriminant(v)?;
209 // There are 3 cases where downcasts can turn a Scalar/ScalarPair into a different ABI which
210 // could be a problem for `ImmTy` (see layout_sanity_check):
211 // - variant.size == Size::ZERO: works fine because `ImmTy::offset` has a special case for
212 // zero-sized layouts.
213 // - variant.fields.count() == 0: works fine because `ImmTy::offset` has a special case for
214 // zero-field aggregates.
215 // - variant.abi.is_uninhabited(): triggers UB in `read_discriminant` so we never get here.
216 let inner = self.ecx().project_downcast(v, idx)?;
217 trace!("walk_value: variant layout: {:#?}", inner.layout());
218 // recurse with the inner type
219 self.visit_variant(v, idx, &inner)?;
220 }
221 // For single-variant layouts, we already did everything there is to do.
222 Variants::Single { .. } | Variants::Empty => {}
223 }
224
225 interp_ok(())
226 }
227}