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_field(v, FieldIdx::ZERO)?,
126 self.ecx().project_field(v, FieldIdx::ONE)?,
127 );
128 // Unfortunately there is some type junk in the way here: `unique_ptr` is a `Unique`...
129 // (which means another 2 fields, the second of which is a `PhantomData`)
130 assert_eq!(unique_ptr.layout().fields.count(), 2);
131 let (nonnull_ptr, phantom) = (
132 self.ecx().project_field(&unique_ptr, FieldIdx::ZERO)?,
133 self.ecx().project_field(&unique_ptr, FieldIdx::ONE)?,
134 );
135 assert!(
136 phantom.layout().ty.ty_adt_def().is_some_and(|adt| adt.is_phantom_data()),
137 "2nd field of `Unique` should be PhantomData but is {:?}",
138 phantom.layout().ty,
139 );
140 // ... that contains a `NonNull`... (gladly, only a single field here)
141 assert_eq!(nonnull_ptr.layout().fields.count(), 1);
142 let raw_ptr = self.ecx().project_field(&nonnull_ptr, FieldIdx::ZERO)?; // the actual raw ptr
143 // ... whose only field finally is a raw ptr we can dereference.
144 self.visit_box(ty, &raw_ptr)?;
145
146 // The second `Box` field is the allocator, which we recursively check for validity
147 // like in regular structs.
148 self.visit_field(v, 1, &alloc)?;
149
150 // We visited all parts of this one.
151 return interp_ok(());
152 }
153
154 // Non-normalized types should never show up here.
155 ty::Param(..)
156 | ty::Alias(..)
157 | ty::Bound(..)
158 | ty::Placeholder(..)
159 | ty::Infer(..)
160 | ty::Error(..) => throw_inval!(TooGeneric),
161
162 // The rest is handled below.
163 _ => {}
164 };
165
166 // Visit the fields of this value.
167 match &v.layout().fields {
168 FieldsShape::Primitive => {}
169 &FieldsShape::Union(fields) => {
170 self.visit_union(v, fields)?;
171 }
172 FieldsShape::Arbitrary { memory_index, .. } => {
173 for idx in Self::aggregate_field_iter(memory_index) {
174 let field = self.ecx().project_field(v, idx)?;
175 self.visit_field(v, idx.as_usize(), &field)?;
176 }
177 }
178 FieldsShape::Array { .. } => {
179 let mut iter = self.ecx().project_array_fields(v)?;
180 while let Some((idx, field)) = iter.next(self.ecx())? {
181 self.visit_field(v, idx.try_into().unwrap(), &field)?;
182 }
183 }
184 }
185
186 match v.layout().variants {
187 // If this is a multi-variant layout, find the right variant and proceed
188 // with *its* fields.
189 Variants::Multiple { .. } => {
190 let idx = self.read_discriminant(v)?;
191 // There are 3 cases where downcasts can turn a Scalar/ScalarPair into a different ABI which
192 // could be a problem for `ImmTy` (see layout_sanity_check):
193 // - variant.size == Size::ZERO: works fine because `ImmTy::offset` has a special case for
194 // zero-sized layouts.
195 // - variant.fields.count() == 0: works fine because `ImmTy::offset` has a special case for
196 // zero-field aggregates.
197 // - variant.abi.is_uninhabited(): triggers UB in `read_discriminant` so we never get here.
198 let inner = self.ecx().project_downcast(v, idx)?;
199 trace!("walk_value: variant layout: {:#?}", inner.layout());
200 // recurse with the inner type
201 self.visit_variant(v, idx, &inner)?;
202 }
203 // For single-variant layouts, we already did everything there is to do.
204 Variants::Single { .. } | Variants::Empty => {}
205 }
206
207 interp_ok(())
208 }
209}