1//! Structural const qualification.
2//!
3//! See the `Qualif` trait for more info.
45// 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.
78use rustc_errors::ErrorGuaranteed;
9use rustc_hir::LangItem;
10use rustc_infer::infer::TyCtxtInferExt;
11use rustc_middle::mir::*;
12use rustc_middle::ty::{self, AdtDef, Ty, TypingMode};
13use rustc_middle::{bug, mir};
14use rustc_trait_selection::traits::{Obligation, ObligationCause, ObligationCtxt};
15use tracing::instrument;
1617use super::ConstCx;
1819pub fn in_any_value_of_ty<'tcx>(
20 cx: &ConstCx<'_, 'tcx>,
21 ty: Ty<'tcx>,
22 tainted_by_errors: Option<ErrorGuaranteed>,
23) -> ConstQualifs {
24ConstQualifs {
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),
28tainted_by_errors,
29 }
30}
3132/// 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.
45const ANALYSIS_NAME: &'static str;
4647/// Whether this `Qualif` is cleared when a local is moved from.
48const IS_CLEARED_ON_MOVE: bool = false;
4950/// Whether this `Qualif` might be evaluated after the promotion and can encounter a promoted.
51const ALLOW_PROMOTED: bool = false;
5253/// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`.
54fn in_qualifs(qualifs: &ConstQualifs) -> bool;
5556/// 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.
63fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool;
6465/// 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.
70fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool;
71}
7273/// 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;
7980impl Qualiffor HasMutInterior {
81const ANALYSIS_NAME: &'static str = "flow_has_mut_interior";
8283fn in_qualifs(qualifs: &ConstQualifs) -> bool {
84qualifs.has_mut_interior
85 }
8687fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
88// Avoid selecting for simple cases, such as builtin types.
89if ty.is_trivially_freeze() {
90return false;
91 }
9293// Avoid selecting for `UnsafeCell` either.
94if ty.ty_adt_def().is_some_and(|adt| adt.is_unsafe_cell()) {
95return true;
96 }
9798// 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.
102let freeze_def_id = cx.tcx.require_lang_item(LangItem::Freeze, cx.body.span);
103let did = cx.body.source.def_id().expect_local();
104105let typing_env = if cx.tcx.use_typing_mode_borrowck() {
106cx.typing_env
107 } else {
108 ty::TypingEnv::new(cx.typing_env.param_env, TypingMode::analysis_in_body(cx.tcx, did))
109 };
110111let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(typing_env);
112let ocx = ObligationCtxt::new(&infcx);
113let obligation = Obligation::new(
114cx.tcx,
115ObligationCause::dummy_with_span(cx.body.span),
116param_env,
117 ty::TraitRef::new(cx.tcx, freeze_def_id, [ty::GenericArg::from(ty)]),
118 );
119ocx.register_obligation(obligation);
120let errors = ocx.evaluate_obligations_error_on_ambiguity();
121 !errors.is_empty()
122 }
123124fn is_structural_in_adt_value<'tcx>(_cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
125// Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently.
126 // It arises structurally for all other types.
127!adt.is_unsafe_cell()
128 }
129}
130131/// Constant containing an ADT that implements `Drop`.
132/// This must be ruled out because implicit promotion would remove side-effects
133/// that occur as part of dropping that value. N.B., the implicit promotion has
134/// to reject const Drop implementations because even if side-effects are ruled
135/// out through other means, the execution of the drop could diverge.
136pub struct NeedsDrop;
137138impl Qualiffor NeedsDrop {
139const ANALYSIS_NAME: &'static str = "flow_needs_drop";
140const IS_CLEARED_ON_MOVE: bool = true;
141const ALLOW_PROMOTED: bool = true;
142143fn in_qualifs(qualifs: &ConstQualifs) -> bool {
144qualifs.needs_drop
145 }
146147fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
148ty.needs_drop(cx.tcx, cx.typing_env)
149 }
150151fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
152 !adt.has_dtor(cx.tcx)
153 }
154}
155156/// Constant containing an ADT that implements non-const `Drop`.
157/// This must be ruled out because we cannot run `Drop` during compile-time.
158pub struct NeedsNonConstDrop;
159160impl Qualiffor NeedsNonConstDrop {
161const ANALYSIS_NAME: &'static str = "flow_needs_nonconst_drop";
162const IS_CLEARED_ON_MOVE: bool = true;
163const ALLOW_PROMOTED: bool = true;
164165fn in_qualifs(qualifs: &ConstQualifs) -> bool {
166qualifs.needs_non_const_drop
167 }
168169x;#[instrument(level = "trace", skip(cx), ret)]170fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
171// If this doesn't need drop at all, then don't select `[const] Destruct`.
172if !ty.needs_drop(cx.tcx, cx.typing_env) {
173return false;
174 }
175176// We check that the type is `[const] Destruct` since that will verify that
177 // the type is both `[const] Drop` (if a drop impl exists for the adt), *and*
178 // that the components of this type are also `[const] Destruct`. This
179 // amounts to verifying that there are no values in this ADT that may have
180 // a non-const drop.
181let destruct_def_id = cx.tcx.require_lang_item(LangItem::Destruct, cx.body.span);
182let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env);
183let ocx = ObligationCtxt::new(&infcx);
184 ocx.register_obligation(Obligation::new(
185 cx.tcx,
186 ObligationCause::misc(cx.body.span, cx.def_id()),
187 param_env,
188 ty::Binder::dummy(ty::TraitRef::new(cx.tcx, destruct_def_id, [ty]))
189 .to_host_effect_clause(
190 cx.tcx,
191match cx.const_kind() {
192 rustc_hir::ConstContext::ConstFn => ty::BoundConstness::Maybe,
193 rustc_hir::ConstContext::Static(_)
194 | rustc_hir::ConstContext::Const { .. } => ty::BoundConstness::Const,
195 },
196 ),
197 ));
198 !ocx.evaluate_obligations_error_on_ambiguity().is_empty()
199 }
200201fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
202// As soon as an ADT has a destructor, then the drop becomes non-structural
203 // in its value since:
204 // 1. The destructor may have `[const]` bounds which are not present on the type.
205 // Someone needs to check that those are satisfied.
206 // While this could be instead satisfied by checking that the `[const] Drop`
207 // impl holds (i.e. replicating part of the `in_any_value_of_ty` logic above),
208 // even in this case, we have another problem, which is,
209 // 2. The destructor may *modify* the operand being dropped, so even if we
210 // did recurse on the components of the operand, we may not be even dropping
211 // the same values that were present before the custom destructor was invoked.
212!adt.has_dtor(cx.tcx)
213 }
214}
215216// FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
217218/// Returns `true` if this `Rvalue` contains qualif `Q`.
219pub fn in_rvalue<'tcx, Q, F>(
220 cx: &ConstCx<'_, 'tcx>,
221 in_local: &mut F,
222 rvalue: &Rvalue<'tcx>,
223) -> bool224where
225Q: Qualif,
226 F: FnMut(Local) -> bool,
227{
228match rvalue {
229 Rvalue::ThreadLocalRef(_) => Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)),
230231 Rvalue::Discriminant(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
232233 Rvalue::CopyForDeref(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
234235 Rvalue::Use(operand, _)
236 | Rvalue::Repeat(operand, _)
237 | Rvalue::UnaryOp(_, operand)
238 | Rvalue::Cast(_, operand, _) => in_operand::<Q, _>(cx, in_local, operand),
239240 Rvalue::BinaryOp(_, (lhs, rhs)) => {
241in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
242 }
243244 Rvalue::Ref(_, _, place) | Rvalue::RawPtr(_, place) => {
245// Special-case reborrows to be more like a copy of the reference.
246if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
247let base_ty = place_base.ty(cx.body, cx.tcx).ty;
248if let ty::Ref(..) = base_ty.kind() {
249return in_place::<Q, _>(cx, in_local, place_base);
250 }
251 }
252253in_place::<Q, _>(cx, in_local, place.as_ref())
254 }
255256 Rvalue::Reborrow(_, _, place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
257258 Rvalue::WrapUnsafeBinder(op, _) => in_operand::<Q, _>(cx, in_local, op),
259260 Rvalue::Aggregate(kind, operands) => {
261// Return early if we know that the struct or enum being constructed is always
262 // qualified.
263if let AggregateKind::Adt(adt_did, ..) = **kind {
264let def = cx.tcx.adt_def(adt_did);
265// Don't do any value-based reasoning for unions.
266 // Also, if the ADT is not structural in its fields,
267 // then we cannot recurse on its fields. Instead,
268 // we fall back to checking the qualif for *any* value
269 // of the ADT.
270if def.is_union() || !Q::is_structural_in_adt_value(cx, def) {
271return Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx));
272 }
273 }
274275// Otherwise, proceed structurally...
276operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o))
277 }
278 }
279}
280281/// Returns `true` if this `Place` contains qualif `Q`.
282pub fn in_place<'tcx, Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool283where
284Q: Qualif,
285 F: FnMut(Local) -> bool,
286{
287let mut place = place;
288while let Some((place_base, elem)) = place.last_projection() {
289match elem {
290 ProjectionElem::Index(index) if in_local(index) => return true,
291292 ProjectionElem::Deref
293 | ProjectionElem::Field(_, _)
294 | ProjectionElem::OpaqueCast(_)
295 | ProjectionElem::ConstantIndex { .. }
296 | ProjectionElem::Subslice { .. }
297 | ProjectionElem::Downcast(_, _)
298 | ProjectionElem::Index(_)
299 | ProjectionElem::UnwrapUnsafeBinder(_) => {}
300 }
301302let base_ty = place_base.ty(cx.body, cx.tcx);
303let proj_ty = base_ty.projection_ty(cx.tcx, elem).ty;
304if !Q::in_any_value_of_ty(cx, proj_ty) {
305return false;
306 }
307308// `Deref` currently unconditionally "qualifies" if `in_any_value_of_ty` returns true,
309 // i.e., we treat all qualifs as non-structural for deref projections. Generally,
310 // we can say very little about `*ptr` even if we know that `ptr` satisfies all
311 // sorts of properties.
312if elem == ProjectionElem::Deref {
313// We have to assume that this qualifies.
314return true;
315 }
316317 place = place_base;
318 }
319320if !place.projection.is_empty() {
::core::panicking::panic("assertion failed: place.projection.is_empty()")
};assert!(place.projection.is_empty());
321in_local(place.local)
322}
323324/// Returns `true` if this `Operand` contains qualif `Q`.
325pub fn in_operand<'tcx, Q, F>(
326 cx: &ConstCx<'_, 'tcx>,
327 in_local: &mut F,
328 operand: &Operand<'tcx>,
329) -> bool330where
331Q: Qualif,
332 F: FnMut(Local) -> bool,
333{
334let constant = match operand {
335 Operand::Copy(place) | Operand::Move(place) => {
336return in_place::<Q, _>(cx, in_local, place.as_ref());
337 }
338 Operand::RuntimeChecks(_) => return Q::in_any_value_of_ty(cx, cx.tcx.types.bool),
339340 Operand::Constant(c) => c,
341 };
342343// Check the qualifs of the value of `const` items.
344let uneval = match constant.const_ {
345 Const::Ty(_, ct) => match ct.kind() {
346 ty::ConstKind::Param(_) | ty::ConstKind::Error(_) => None,
347// Unevaluated consts in MIR bodies don't have associated MIR (e.g. `type const`).
348ty::ConstKind::Unevaluated(_) => None,
349// FIXME(mgca): Investigate whether using `None` for `ConstKind::Value` is overly
350 // strict, and if instead we should be doing some kind of value-based analysis.
351ty::ConstKind::Value(_) => None,
352_ => ::rustc_middle::util::bug::bug_fmt(format_args!("expected ConstKind::Param, ConstKind::Value, ConstKind::Unevaluated, or ConstKind::Error here, found {0:?}",
ct))bug!(
353"expected ConstKind::Param, ConstKind::Value, ConstKind::Unevaluated, or ConstKind::Error here, found {:?}",
354 ct
355 ),
356 },
357 Const::Unevaluated(uv, _) => Some(uv),
358 Const::Val(..) => None,
359 };
360361if let Some(mir::UnevaluatedConst { def, args: _, promoted }) = uneval {
362// Use qualifs of the type for the promoted. Promoteds in MIR body should be possible
363 // only for `NeedsNonConstDrop` with precise drop checking. This is the only const
364 // check performed after the promotion. Verify that with an assertion.
365if !(promoted.is_none() || Q::ALLOW_PROMOTED) {
::core::panicking::panic("assertion failed: promoted.is_none() || Q::ALLOW_PROMOTED")
};assert!(promoted.is_none() || Q::ALLOW_PROMOTED);
366367// Don't peak inside trait associated constants.
368if promoted.is_none() && cx.tcx.trait_of_assoc(def).is_none() {
369let qualifs = cx.tcx.at(constant.span).mir_const_qualif(def);
370371if !Q::in_qualifs(&qualifs) {
372return false;
373 }
374375// Just in case the type is more specific than
376 // the definition, e.g., impl associated const
377 // with type parameters, take it into account.
378}
379 }
380381// Otherwise use the qualifs of the type.
382Q::in_any_value_of_ty(cx, constant.const_.ty())
383}