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