rustc_const_eval/check_consts/qualifs.rs
1//! Structural const qualification.
2//!
3//! See the `Qualif` trait for more info.
4
5// FIXME(const_trait_impl): This API should be really reworked. It's dangerously general for
6// having basically only two use-cases that act in different ways.
7
8use rustc_errors::ErrorGuaranteed;
9use rustc_hir::LangItem;
10use rustc_infer::infer::TyCtxtInferExt;
11use rustc_middle::mir::*;
12use rustc_middle::ty::{self, AdtDef, Ty};
13use rustc_middle::{bug, mir};
14use rustc_trait_selection::traits::{Obligation, ObligationCause, ObligationCtxt};
15use tracing::instrument;
16
17use super::ConstCx;
18
19pub fn in_any_value_of_ty<'tcx>(
20 cx: &ConstCx<'_, 'tcx>,
21 ty: Ty<'tcx>,
22 tainted_by_errors: Option<ErrorGuaranteed>,
23) -> ConstQualifs {
24 ConstQualifs {
25 has_mut_interior: HasMutInterior::in_any_value_of_ty(cx, ty),
26 needs_drop: NeedsDrop::in_any_value_of_ty(cx, ty),
27 needs_non_const_drop: NeedsNonConstDrop::in_any_value_of_ty(cx, ty),
28 tainted_by_errors,
29 }
30}
31
32/// A "qualif"(-ication) is a way to look for something "bad" in the MIR that would disqualify some
33/// code for promotion or prevent it from evaluating at compile time.
34///
35/// Normally, we would determine what qualifications apply to each type and error when an illegal
36/// operation is performed on such a type. However, this was found to be too imprecise, especially
37/// in the presence of `enum`s. If only a single variant of an enum has a certain qualification, we
38/// needn't reject code unless it actually constructs and operates on the qualified variant.
39///
40/// To accomplish this, const-checking and promotion use a value-based analysis (as opposed to a
41/// type-based one). Qualifications propagate structurally across variables: If a local (or a
42/// projection of a local) is assigned a qualified value, that local itself becomes qualified.
43pub trait Qualif {
44 /// The name of the file used to debug the dataflow analysis that computes this qualif.
45 const ANALYSIS_NAME: &'static str;
46
47 /// Whether this `Qualif` is cleared when a local is moved from.
48 const IS_CLEARED_ON_MOVE: bool = false;
49
50 /// Whether this `Qualif` might be evaluated after the promotion and can encounter a promoted.
51 const ALLOW_PROMOTED: bool = false;
52
53 /// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`.
54 fn in_qualifs(qualifs: &ConstQualifs) -> bool;
55
56 /// Returns `true` if *any* value of the given type could possibly have this `Qualif`.
57 ///
58 /// This function determines `Qualif`s when we cannot do a value-based analysis. Since qualif
59 /// propagation is context-insensitive, this includes function arguments and values returned
60 /// from a call to another function.
61 ///
62 /// It also determines the `Qualif`s for primitive types.
63 fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool;
64
65 /// Returns `true` if the `Qualif` is structural in an ADT's fields, i.e. if we may
66 /// recurse into an operand *value* to determine whether it has this `Qualif`.
67 ///
68 /// If this returns false, `in_any_value_of_ty` will be invoked to determine the
69 /// final qualif for this ADT.
70 fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool;
71}
72
73/// Constant containing interior mutability (`UnsafeCell<T>`).
74/// This must be ruled out to make sure that evaluating the constant at compile-time
75/// and at *any point* during the run-time would produce the same result. In particular,
76/// promotion of temporaries must not change program behavior; if the promoted could be
77/// written to, that would be a problem.
78pub struct HasMutInterior;
79
80impl Qualif for HasMutInterior {
81 const ANALYSIS_NAME: &'static str = "flow_has_mut_interior";
82
83 fn in_qualifs(qualifs: &ConstQualifs) -> bool {
84 qualifs.has_mut_interior
85 }
86
87 fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
88 // Avoid selecting for simple cases, such as builtin types.
89 if ty.is_trivially_freeze() {
90 return false;
91 }
92
93 // Avoid selecting for `UnsafeCell` either.
94 if ty.ty_adt_def().is_some_and(|adt| adt.is_unsafe_cell()) {
95 return true;
96 }
97
98 // We do not use `ty.is_freeze` here, because that requires revealing opaque types, which
99 // requires borrowck, which in turn will invoke mir_const_qualifs again, causing a cycle error.
100 // Instead we invoke an obligation context manually, and provide the opaque type inference settings
101 // that allow the trait solver to just error out instead of cycling.
102 let freeze_def_id = cx.tcx.require_lang_item(LangItem::Freeze, Some(cx.body.span));
103 // FIXME(#132279): Once we've got a typing mode which reveals opaque types using the HIR
104 // typeck results without causing query cycles, we should use this here instead of defining
105 // opaque types.
106 let typing_env = ty::TypingEnv {
107 typing_mode: ty::TypingMode::analysis_in_body(
108 cx.tcx,
109 cx.body.source.def_id().expect_local(),
110 ),
111 param_env: cx.typing_env.param_env,
112 };
113 let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(typing_env);
114 let ocx = ObligationCtxt::new(&infcx);
115 let obligation = Obligation::new(
116 cx.tcx,
117 ObligationCause::dummy_with_span(cx.body.span),
118 param_env,
119 ty::TraitRef::new(cx.tcx, freeze_def_id, [ty::GenericArg::from(ty)]),
120 );
121 ocx.register_obligation(obligation);
122 let errors = ocx.select_all_or_error();
123 !errors.is_empty()
124 }
125
126 fn is_structural_in_adt_value<'tcx>(_cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
127 // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently.
128 // It arises structurally for all other types.
129 !adt.is_unsafe_cell()
130 }
131}
132
133/// Constant containing an ADT that implements `Drop`.
134/// This must be ruled out because implicit promotion would remove side-effects
135/// that occur as part of dropping that value. N.B., the implicit promotion has
136/// to reject const Drop implementations because even if side-effects are ruled
137/// out through other means, the execution of the drop could diverge.
138pub struct NeedsDrop;
139
140impl Qualif for NeedsDrop {
141 const ANALYSIS_NAME: &'static str = "flow_needs_drop";
142 const IS_CLEARED_ON_MOVE: bool = true;
143 const ALLOW_PROMOTED: bool = true;
144
145 fn in_qualifs(qualifs: &ConstQualifs) -> bool {
146 qualifs.needs_drop
147 }
148
149 fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
150 ty.needs_drop(cx.tcx, cx.typing_env)
151 }
152
153 fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
154 !adt.has_dtor(cx.tcx)
155 }
156}
157
158/// Constant containing an ADT that implements non-const `Drop`.
159/// This must be ruled out because we cannot run `Drop` during compile-time.
160pub struct NeedsNonConstDrop;
161
162impl Qualif for NeedsNonConstDrop {
163 const ANALYSIS_NAME: &'static str = "flow_needs_nonconst_drop";
164 const IS_CLEARED_ON_MOVE: bool = true;
165 const ALLOW_PROMOTED: bool = true;
166
167 fn in_qualifs(qualifs: &ConstQualifs) -> bool {
168 qualifs.needs_non_const_drop
169 }
170
171 #[instrument(level = "trace", skip(cx), ret)]
172 fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
173 // If this doesn't need drop at all, then don't select `~const Destruct`.
174 if !ty.needs_drop(cx.tcx, cx.typing_env) {
175 return false;
176 }
177
178 // We check that the type is `~const Destruct` since that will verify that
179 // the type is both `~const Drop` (if a drop impl exists for the adt), *and*
180 // that the components of this type are also `~const Destruct`. This
181 // amounts to verifying that there are no values in this ADT that may have
182 // a non-const drop.
183 let destruct_def_id = cx.tcx.require_lang_item(LangItem::Destruct, Some(cx.body.span));
184 let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env);
185 let ocx = ObligationCtxt::new(&infcx);
186 ocx.register_obligation(Obligation::new(
187 cx.tcx,
188 ObligationCause::misc(cx.body.span, cx.def_id()),
189 param_env,
190 ty::Binder::dummy(ty::TraitRef::new(cx.tcx, destruct_def_id, [ty]))
191 .to_host_effect_clause(
192 cx.tcx,
193 match cx.const_kind() {
194 rustc_hir::ConstContext::ConstFn => ty::BoundConstness::Maybe,
195 rustc_hir::ConstContext::Static(_)
196 | rustc_hir::ConstContext::Const { .. } => ty::BoundConstness::Const,
197 },
198 ),
199 ));
200 !ocx.select_all_or_error().is_empty()
201 }
202
203 fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
204 // As soon as an ADT has a destructor, then the drop becomes non-structural
205 // in its value since:
206 // 1. The destructor may have `~const` bounds which are not present on the type.
207 // Someone needs to check that those are satisfied.
208 // While this could be instead satisfied by checking that the `~const Drop`
209 // impl holds (i.e. replicating part of the `in_any_value_of_ty` logic above),
210 // even in this case, we have another problem, which is,
211 // 2. The destructor may *modify* the operand being dropped, so even if we
212 // did recurse on the components of the operand, we may not be even dropping
213 // the same values that were present before the custom destructor was invoked.
214 !adt.has_dtor(cx.tcx)
215 }
216}
217
218// FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
219
220/// Returns `true` if this `Rvalue` contains qualif `Q`.
221pub fn in_rvalue<'tcx, Q, F>(
222 cx: &ConstCx<'_, 'tcx>,
223 in_local: &mut F,
224 rvalue: &Rvalue<'tcx>,
225) -> bool
226where
227 Q: Qualif,
228 F: FnMut(Local) -> bool,
229{
230 match rvalue {
231 Rvalue::ThreadLocalRef(_) | Rvalue::NullaryOp(..) => {
232 Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx))
233 }
234
235 Rvalue::Discriminant(place) | Rvalue::Len(place) => {
236 in_place::<Q, _>(cx, in_local, place.as_ref())
237 }
238
239 Rvalue::CopyForDeref(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
240
241 Rvalue::Use(operand)
242 | Rvalue::Repeat(operand, _)
243 | Rvalue::UnaryOp(_, operand)
244 | Rvalue::Cast(_, operand, _)
245 | Rvalue::ShallowInitBox(operand, _) => in_operand::<Q, _>(cx, in_local, operand),
246
247 Rvalue::BinaryOp(_, box (lhs, rhs)) => {
248 in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
249 }
250
251 Rvalue::Ref(_, _, place) | Rvalue::RawPtr(_, place) => {
252 // Special-case reborrows to be more like a copy of the reference.
253 if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
254 let base_ty = place_base.ty(cx.body, cx.tcx).ty;
255 if let ty::Ref(..) = base_ty.kind() {
256 return in_place::<Q, _>(cx, in_local, place_base);
257 }
258 }
259
260 in_place::<Q, _>(cx, in_local, place.as_ref())
261 }
262
263 Rvalue::WrapUnsafeBinder(op, _) => in_operand::<Q, _>(cx, in_local, op),
264
265 Rvalue::Aggregate(kind, operands) => {
266 // Return early if we know that the struct or enum being constructed is always
267 // qualified.
268 if let AggregateKind::Adt(adt_did, ..) = **kind {
269 let def = cx.tcx.adt_def(adt_did);
270 // Don't do any value-based reasoning for unions.
271 // Also, if the ADT is not structural in its fields,
272 // then we cannot recurse on its fields. Instead,
273 // we fall back to checking the qualif for *any* value
274 // of the ADT.
275 if def.is_union() || !Q::is_structural_in_adt_value(cx, def) {
276 return Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx));
277 }
278 }
279
280 // Otherwise, proceed structurally...
281 operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o))
282 }
283 }
284}
285
286/// Returns `true` if this `Place` contains qualif `Q`.
287pub fn in_place<'tcx, Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool
288where
289 Q: Qualif,
290 F: FnMut(Local) -> bool,
291{
292 let mut place = place;
293 while let Some((place_base, elem)) = place.last_projection() {
294 match elem {
295 ProjectionElem::Index(index) if in_local(index) => return true,
296
297 ProjectionElem::Deref
298 | ProjectionElem::Subtype(_)
299 | ProjectionElem::Field(_, _)
300 | ProjectionElem::OpaqueCast(_)
301 | ProjectionElem::ConstantIndex { .. }
302 | ProjectionElem::Subslice { .. }
303 | ProjectionElem::Downcast(_, _)
304 | ProjectionElem::Index(_)
305 | ProjectionElem::UnwrapUnsafeBinder(_) => {}
306 }
307
308 let base_ty = place_base.ty(cx.body, cx.tcx);
309 let proj_ty = base_ty.projection_ty(cx.tcx, elem).ty;
310 if !Q::in_any_value_of_ty(cx, proj_ty) {
311 return false;
312 }
313
314 // `Deref` currently unconditionally "qualifies" if `in_any_value_of_ty` returns true,
315 // i.e., we treat all qualifs as non-structural for deref projections. Generally,
316 // we can say very little about `*ptr` even if we know that `ptr` satisfies all
317 // sorts of properties.
318 if matches!(elem, ProjectionElem::Deref) {
319 // We have to assume that this qualifies.
320 return true;
321 }
322
323 place = place_base;
324 }
325
326 assert!(place.projection.is_empty());
327 in_local(place.local)
328}
329
330/// Returns `true` if this `Operand` contains qualif `Q`.
331pub fn in_operand<'tcx, Q, F>(
332 cx: &ConstCx<'_, 'tcx>,
333 in_local: &mut F,
334 operand: &Operand<'tcx>,
335) -> bool
336where
337 Q: Qualif,
338 F: FnMut(Local) -> bool,
339{
340 let constant = match operand {
341 Operand::Copy(place) | Operand::Move(place) => {
342 return in_place::<Q, _>(cx, in_local, place.as_ref());
343 }
344
345 Operand::Constant(c) => c,
346 };
347
348 // Check the qualifs of the value of `const` items.
349 let uneval = match constant.const_ {
350 Const::Ty(_, ct)
351 if matches!(
352 ct.kind(),
353 ty::ConstKind::Param(_) | ty::ConstKind::Error(_) | ty::ConstKind::Value(_)
354 ) =>
355 {
356 None
357 }
358 Const::Ty(_, c) => {
359 bug!("expected ConstKind::Param or ConstKind::Value here, found {:?}", c)
360 }
361 Const::Unevaluated(uv, _) => Some(uv),
362 Const::Val(..) => None,
363 };
364
365 if let Some(mir::UnevaluatedConst { def, args: _, promoted }) = uneval {
366 // Use qualifs of the type for the promoted. Promoteds in MIR body should be possible
367 // only for `NeedsNonConstDrop` with precise drop checking. This is the only const
368 // check performed after the promotion. Verify that with an assertion.
369 assert!(promoted.is_none() || Q::ALLOW_PROMOTED);
370
371 // Don't peek inside trait associated constants.
372 if promoted.is_none() && cx.tcx.trait_of_item(def).is_none() {
373 let qualifs = cx.tcx.at(constant.span).mir_const_qualif(def);
374
375 if !Q::in_qualifs(&qualifs) {
376 return false;
377 }
378
379 // Just in case the type is more specific than
380 // the definition, e.g., impl associated const
381 // with type parameters, take it into account.
382 }
383 }
384
385 // Otherwise use the qualifs of the type.
386 Q::in_any_value_of_ty(cx, constant.const_.ty())
387}