Skip to main content

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, 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::new(
107            cx.typing_env.param_env,
108            ty::TypingMode::analysis_in_body(cx.tcx, cx.body.source.def_id().expect_local()),
109        );
110        let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(typing_env);
111        let ocx = ObligationCtxt::new(&infcx);
112        let obligation = Obligation::new(
113            cx.tcx,
114            ObligationCause::dummy_with_span(cx.body.span),
115            param_env,
116            ty::TraitRef::new(cx.tcx, freeze_def_id, [ty::GenericArg::from(ty)]),
117        );
118        ocx.register_obligation(obligation);
119        let errors = ocx.evaluate_obligations_error_on_ambiguity();
120        !errors.is_empty()
121    }
122
123    fn is_structural_in_adt_value<'tcx>(_cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
124        // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently.
125        // It arises structurally for all other types.
126        !adt.is_unsafe_cell()
127    }
128}
129
130/// Constant containing an ADT that implements `Drop`.
131/// This must be ruled out because implicit promotion would remove side-effects
132/// that occur as part of dropping that value. N.B., the implicit promotion has
133/// to reject const Drop implementations because even if side-effects are ruled
134/// out through other means, the execution of the drop could diverge.
135pub struct NeedsDrop;
136
137impl Qualif for NeedsDrop {
138    const ANALYSIS_NAME: &'static str = "flow_needs_drop";
139    const IS_CLEARED_ON_MOVE: bool = true;
140    const ALLOW_PROMOTED: bool = true;
141
142    fn in_qualifs(qualifs: &ConstQualifs) -> bool {
143        qualifs.needs_drop
144    }
145
146    fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
147        ty.needs_drop(cx.tcx, cx.typing_env)
148    }
149
150    fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
151        !adt.has_dtor(cx.tcx)
152    }
153}
154
155/// Constant containing an ADT that implements non-const `Drop`.
156/// This must be ruled out because we cannot run `Drop` during compile-time.
157pub struct NeedsNonConstDrop;
158
159impl Qualif for NeedsNonConstDrop {
160    const ANALYSIS_NAME: &'static str = "flow_needs_nonconst_drop";
161    const IS_CLEARED_ON_MOVE: bool = true;
162    const ALLOW_PROMOTED: bool = true;
163
164    fn in_qualifs(qualifs: &ConstQualifs) -> bool {
165        qualifs.needs_non_const_drop
166    }
167
168    x;#[instrument(level = "trace", skip(cx), ret)]
169    fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
170        // If this doesn't need drop at all, then don't select `[const] Destruct`.
171        if !ty.needs_drop(cx.tcx, cx.typing_env) {
172            return false;
173        }
174
175        // We check that the type is `[const] Destruct` since that will verify that
176        // the type is both `[const] Drop` (if a drop impl exists for the adt), *and*
177        // that the components of this type are also `[const] Destruct`. This
178        // amounts to verifying that there are no values in this ADT that may have
179        // a non-const drop.
180        let destruct_def_id = cx.tcx.require_lang_item(LangItem::Destruct, cx.body.span);
181        let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env);
182        let ocx = ObligationCtxt::new(&infcx);
183        ocx.register_obligation(Obligation::new(
184            cx.tcx,
185            ObligationCause::misc(cx.body.span, cx.def_id()),
186            param_env,
187            ty::Binder::dummy(ty::TraitRef::new(cx.tcx, destruct_def_id, [ty]))
188                .to_host_effect_clause(
189                    cx.tcx,
190                    match cx.const_kind() {
191                        rustc_hir::ConstContext::ConstFn => ty::BoundConstness::Maybe,
192                        rustc_hir::ConstContext::Static(_)
193                        | rustc_hir::ConstContext::Const { .. } => ty::BoundConstness::Const,
194                    },
195                ),
196        ));
197        !ocx.evaluate_obligations_error_on_ambiguity().is_empty()
198    }
199
200    fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
201        // As soon as an ADT has a destructor, then the drop becomes non-structural
202        // in its value since:
203        // 1. The destructor may have `[const]` bounds which are not present on the type.
204        //   Someone needs to check that those are satisfied.
205        //   While this could be instead satisfied by checking that the `[const] Drop`
206        //   impl holds (i.e. replicating part of the `in_any_value_of_ty` logic above),
207        //   even in this case, we have another problem, which is,
208        // 2. The destructor may *modify* the operand being dropped, so even if we
209        //   did recurse on the components of the operand, we may not be even dropping
210        //   the same values that were present before the custom destructor was invoked.
211        !adt.has_dtor(cx.tcx)
212    }
213}
214
215// FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
216
217/// Returns `true` if this `Rvalue` contains qualif `Q`.
218pub fn in_rvalue<'tcx, Q, F>(
219    cx: &ConstCx<'_, 'tcx>,
220    in_local: &mut F,
221    rvalue: &Rvalue<'tcx>,
222) -> bool
223where
224    Q: Qualif,
225    F: FnMut(Local) -> bool,
226{
227    match rvalue {
228        Rvalue::ThreadLocalRef(_) => Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)),
229
230        Rvalue::Discriminant(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
231
232        Rvalue::CopyForDeref(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
233
234        Rvalue::Use(operand)
235        | Rvalue::Repeat(operand, _)
236        | Rvalue::UnaryOp(_, operand)
237        | Rvalue::Cast(_, operand, _) => in_operand::<Q, _>(cx, in_local, operand),
238
239        Rvalue::BinaryOp(_, box (lhs, rhs)) => {
240            in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
241        }
242
243        Rvalue::Ref(_, _, place) | Rvalue::RawPtr(_, place) => {
244            // Special-case reborrows to be more like a copy of the reference.
245            if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
246                let base_ty = place_base.ty(cx.body, cx.tcx).ty;
247                if let ty::Ref(..) = base_ty.kind() {
248                    return in_place::<Q, _>(cx, in_local, place_base);
249                }
250            }
251
252            in_place::<Q, _>(cx, in_local, place.as_ref())
253        }
254
255        Rvalue::WrapUnsafeBinder(op, _) => in_operand::<Q, _>(cx, in_local, op),
256
257        Rvalue::Aggregate(kind, operands) => {
258            // Return early if we know that the struct or enum being constructed is always
259            // qualified.
260            if let AggregateKind::Adt(adt_did, ..) = **kind {
261                let def = cx.tcx.adt_def(adt_did);
262                // Don't do any value-based reasoning for unions.
263                // Also, if the ADT is not structural in its fields,
264                // then we cannot recurse on its fields. Instead,
265                // we fall back to checking the qualif for *any* value
266                // of the ADT.
267                if def.is_union() || !Q::is_structural_in_adt_value(cx, def) {
268                    return Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx));
269                }
270            }
271
272            // Otherwise, proceed structurally...
273            operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o))
274        }
275    }
276}
277
278/// Returns `true` if this `Place` contains qualif `Q`.
279pub fn in_place<'tcx, Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool
280where
281    Q: Qualif,
282    F: FnMut(Local) -> bool,
283{
284    let mut place = place;
285    while let Some((place_base, elem)) = place.last_projection() {
286        match elem {
287            ProjectionElem::Index(index) if in_local(index) => return true,
288
289            ProjectionElem::Deref
290            | ProjectionElem::Field(_, _)
291            | ProjectionElem::OpaqueCast(_)
292            | ProjectionElem::ConstantIndex { .. }
293            | ProjectionElem::Subslice { .. }
294            | ProjectionElem::Downcast(_, _)
295            | ProjectionElem::Index(_)
296            | ProjectionElem::UnwrapUnsafeBinder(_) => {}
297        }
298
299        let base_ty = place_base.ty(cx.body, cx.tcx);
300        let proj_ty = base_ty.projection_ty(cx.tcx, elem).ty;
301        if !Q::in_any_value_of_ty(cx, proj_ty) {
302            return false;
303        }
304
305        // `Deref` currently unconditionally "qualifies" if `in_any_value_of_ty` returns true,
306        // i.e., we treat all qualifs as non-structural for deref projections. Generally,
307        // we can say very little about `*ptr` even if we know that `ptr` satisfies all
308        // sorts of properties.
309        if elem == ProjectionElem::Deref {
310            // We have to assume that this qualifies.
311            return true;
312        }
313
314        place = place_base;
315    }
316
317    if !place.projection.is_empty() {
    ::core::panicking::panic("assertion failed: place.projection.is_empty()")
};assert!(place.projection.is_empty());
318    in_local(place.local)
319}
320
321/// Returns `true` if this `Operand` contains qualif `Q`.
322pub fn in_operand<'tcx, Q, F>(
323    cx: &ConstCx<'_, 'tcx>,
324    in_local: &mut F,
325    operand: &Operand<'tcx>,
326) -> bool
327where
328    Q: Qualif,
329    F: FnMut(Local) -> bool,
330{
331    let constant = match operand {
332        Operand::Copy(place) | Operand::Move(place) => {
333            return in_place::<Q, _>(cx, in_local, place.as_ref());
334        }
335        Operand::RuntimeChecks(_) => return Q::in_any_value_of_ty(cx, cx.tcx.types.bool),
336
337        Operand::Constant(c) => c,
338    };
339
340    // Check the qualifs of the value of `const` items.
341    let uneval = match constant.const_ {
342        Const::Ty(_, ct) => match ct.kind() {
343            ty::ConstKind::Param(_) | ty::ConstKind::Error(_) => None,
344            // Unevaluated consts in MIR bodies don't have associated MIR (e.g. `type const`).
345            ty::ConstKind::Unevaluated(_) => None,
346            // FIXME(mgca): Investigate whether using `None` for `ConstKind::Value` is overly
347            // strict, and if instead we should be doing some kind of value-based analysis.
348            ty::ConstKind::Value(_) => None,
349            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("expected ConstKind::Param, ConstKind::Value, ConstKind::Unevaluated, or ConstKind::Error here, found {0:?}",
        ct))bug!(
350                "expected ConstKind::Param, ConstKind::Value, ConstKind::Unevaluated, or ConstKind::Error here, found {:?}",
351                ct
352            ),
353        },
354        Const::Unevaluated(uv, _) => Some(uv),
355        Const::Val(..) => None,
356    };
357
358    if let Some(mir::UnevaluatedConst { def, args: _, promoted }) = uneval {
359        // Use qualifs of the type for the promoted. Promoteds in MIR body should be possible
360        // only for `NeedsNonConstDrop` with precise drop checking. This is the only const
361        // check performed after the promotion. Verify that with an assertion.
362        if !(promoted.is_none() || Q::ALLOW_PROMOTED) {
    ::core::panicking::panic("assertion failed: promoted.is_none() || Q::ALLOW_PROMOTED")
};assert!(promoted.is_none() || Q::ALLOW_PROMOTED);
363
364        // Don't peak inside trait associated constants.
365        if promoted.is_none() && cx.tcx.trait_of_assoc(def).is_none() {
366            let qualifs = cx.tcx.at(constant.span).mir_const_qualif(def);
367
368            if !Q::in_qualifs(&qualifs) {
369                return false;
370            }
371
372            // Just in case the type is more specific than
373            // the definition, e.g., impl associated const
374            // with type parameters, take it into account.
375        }
376    }
377
378    // Otherwise use the qualifs of the type.
379    Q::in_any_value_of_ty(cx, constant.const_.ty())
380}