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