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::attrs::lang_items::LangItem;
10use rustc_infer::infer::TyCtxtInferExt;
11use rustc_middle::mir;
12use rustc_middle::mir::*;
13use rustc_middle::ty::{self, AdtDef, Ty, TypingMode};
14use rustc_span::bug;
15use rustc_trait_selection::traits::{Obligation, ObligationCause, ObligationCtxt};
16use tracing::instrument;
17
18use super::ConstCx;
19
20pub fn in_any_value_of_ty<'tcx>(
21    cx: &ConstCx<'_, 'tcx>,
22    ty: Ty<'tcx>,
23    tainted_by_errors: Option<ErrorGuaranteed>,
24) -> ConstQualifs {
25    ConstQualifs {
26        has_mut_interior: HasMutInterior::in_any_value_of_ty(cx, ty),
27        needs_drop: NeedsDrop::in_any_value_of_ty(cx, ty),
28        needs_non_const_drop: NeedsNonConstDrop::in_any_value_of_ty(cx, ty),
29        tainted_by_errors,
30    }
31}
32
33/// A "qualif"(-ication) is a way to look for something "bad" in the MIR that would disqualify some
34/// code for promotion or prevent it from evaluating at compile time.
35///
36/// Normally, we would determine what qualifications apply to each type and error when an illegal
37/// operation is performed on such a type. However, this was found to be too imprecise, especially
38/// in the presence of `enum`s. If only a single variant of an enum has a certain qualification, we
39/// needn't reject code unless it actually constructs and operates on the qualified variant.
40///
41/// To accomplish this, const-checking and promotion use a value-based analysis (as opposed to a
42/// type-based one). Qualifications propagate structurally across variables: If a local (or a
43/// projection of a local) is assigned a qualified value, that local itself becomes qualified.
44pub trait Qualif {
45    /// The name of the file used to debug the dataflow analysis that computes this qualif.
46    const ANALYSIS_NAME: &'static str;
47
48    /// Whether this `Qualif` is cleared when a local is moved from.
49    const IS_CLEARED_ON_MOVE: bool;
50
51    /// Whether this `Qualif` might be evaluated after the promotion and can encounter a promoted.
52    const ALLOW_PROMOTED: bool;
53
54    /// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`.
55    fn in_qualifs(qualifs: &ConstQualifs) -> bool;
56
57    /// Returns `true` if *any* value of the given type could possibly have this `Qualif`.
58    ///
59    /// This function determines `Qualif`s when we cannot do a value-based analysis. Since qualif
60    /// propagation is context-insensitive, this includes function arguments and values returned
61    /// from a call to another function.
62    ///
63    /// It also determines the `Qualif`s for primitive types.
64    fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool;
65
66    /// Returns `true` if the `Qualif` is structural in an ADT's fields, i.e. if we may
67    /// recurse into an operand *value* to determine whether it has this `Qualif`.
68    ///
69    /// If this returns false, `in_any_value_of_ty` will be invoked to determine the
70    /// final qualif for this ADT.
71    fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool;
72}
73
74/// Constant containing interior mutability (`UnsafeCell<T>`).
75/// This must be ruled out to make sure that evaluating the constant at compile-time
76/// and at *any point* during the run-time would produce the same result. In particular,
77/// promotion of temporaries must not change program behavior; if the promoted could be
78/// written to, that would be a problem.
79pub struct HasMutInterior;
80
81impl Qualif for HasMutInterior {
82    const ANALYSIS_NAME: &'static str = "flow_has_mut_interior";
83    const IS_CLEARED_ON_MOVE: bool = false;
84    const ALLOW_PROMOTED: bool = false;
85
86    fn in_qualifs(qualifs: &ConstQualifs) -> bool {
87        qualifs.has_mut_interior
88    }
89
90    fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
91        // Avoid selecting for simple cases, such as builtin types.
92        if ty.is_trivially_freeze() {
93            return false;
94        }
95
96        // Avoid selecting for `UnsafeCell` either.
97        if ty.ty_adt_def().is_some_and(|adt| adt.is_unsafe_cell()) {
98            return true;
99        }
100
101        // We do not use `ty.is_freeze` here, because that requires revealing opaque types, which
102        // requires borrowck, which in turn will invoke mir_const_qualifs again, causing a cycle error.
103        // Instead we invoke an obligation context manually, and provide the opaque type inference settings
104        // that allow the trait solver to just error out instead of cycling.
105        let freeze_def_id = cx.tcx.require_lang_item(LangItem::Freeze, cx.body.span);
106        let did = cx.body.source.def_id().expect_local();
107
108        let typing_env = if cx.tcx.use_typing_mode_post_typeck_until_borrowck() {
109            cx.typing_env
110        } else {
111            ty::TypingEnv::new(cx.typing_env.param_env, TypingMode::analysis_in_body(cx.tcx, did))
112        };
113
114        let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(typing_env);
115        let ocx = ObligationCtxt::new(&infcx);
116        let obligation = Obligation::new(
117            cx.tcx,
118            ObligationCause::dummy_with_span(cx.body.span),
119            param_env,
120            ty::TraitRef::new(cx.tcx, freeze_def_id, [ty::GenericArg::from(ty)]),
121        );
122        ocx.register_obligation(obligation);
123        let errors = ocx.evaluate_obligations_error_on_ambiguity();
124        !errors.no_errors()
125    }
126
127    fn is_structural_in_adt_value<'tcx>(_cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
128        // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently.
129        // It arises structurally for all other types.
130        !adt.is_unsafe_cell()
131    }
132}
133
134/// Constant containing an ADT that implements `Drop`.
135/// This must be ruled out because implicit promotion would remove side-effects
136/// that occur as part of dropping that value. N.B., the implicit promotion has
137/// to reject const Drop implementations because even if side-effects are ruled
138/// out through other means, the execution of the drop could diverge.
139pub struct NeedsDrop;
140
141impl Qualif for NeedsDrop {
142    const ANALYSIS_NAME: &'static str = "flow_needs_drop";
143    const IS_CLEARED_ON_MOVE: bool = true;
144    const ALLOW_PROMOTED: bool = true;
145
146    fn in_qualifs(qualifs: &ConstQualifs) -> bool {
147        qualifs.needs_drop
148    }
149
150    fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
151        ty.needs_drop(cx.tcx, cx.typing_env)
152    }
153
154    fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
155        !adt.has_dtor(cx.tcx)
156    }
157}
158
159/// Constant containing an ADT that implements non-const `Drop`.
160/// This must be ruled out because we cannot run `Drop` during compile-time.
161pub struct NeedsNonConstDrop;
162
163impl Qualif for NeedsNonConstDrop {
164    const ANALYSIS_NAME: &'static str = "flow_needs_nonconst_drop";
165    const IS_CLEARED_ON_MOVE: bool = true;
166    const ALLOW_PROMOTED: bool = true;
167
168    fn in_qualifs(qualifs: &ConstQualifs) -> bool {
169        qualifs.needs_non_const_drop
170    }
171
172    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::TRACE <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("in_any_value_of_ty",
                                "rustc_const_eval::check_consts::qualifs",
                                ::tracing::Level::TRACE,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/qualifs.rs"),
                                ::tracing_core::__macro_support::Option::Some(172u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_const_eval::check_consts::qualifs"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("ty")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("ty");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return: bool = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        if !ty.needs_drop(cx.tcx, cx.typing_env) { return false; }
                        let destruct_def_id =
                            cx.tcx.require_lang_item(LangItem::Destruct, cx.body.span);
                        let (infcx, param_env) =
                            cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env);
                        let ocx = ObligationCtxt::new(&infcx);
                        ocx.register_obligation(Obligation::new(cx.tcx,
                                ObligationCause::misc(cx.body.span, cx.def_id()), param_env,
                                ty::Binder::dummy(ty::TraitRef::new(cx.tcx, destruct_def_id,
                                            [ty])).to_host_effect_clause(cx.tcx,
                                    match cx.const_kind() {
                                        rustc_hir::ConstContext::ConstFn =>
                                            ty::BoundConstness::Maybe,
                                        rustc_hir::ConstContext::Static(_) |
                                            rustc_hir::ConstContext::Const { .. } =>
                                            ty::BoundConstness::Const,
                                    })));
                        !ocx.evaluate_obligations_error_on_ambiguity().no_errors()
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/qualifs.rs:172",
                        "rustc_const_eval::check_consts::qualifs",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/qualifs.rs"),
                        ::tracing_core::__macro_support::Option::Some(172u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::check_consts::qualifs"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "trace", skip(cx), ret)]
173    fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
174        // If this doesn't need drop at all, then don't select `[const] Destruct`.
175        if !ty.needs_drop(cx.tcx, cx.typing_env) {
176            return false;
177        }
178
179        // We check that the type is `[const] Destruct` since that will verify that
180        // the type is both `[const] Drop` (if a drop impl exists for the adt), *and*
181        // that the components of this type are also `[const] Destruct`. This
182        // amounts to verifying that there are no values in this ADT that may have
183        // a non-const drop.
184        let destruct_def_id = cx.tcx.require_lang_item(LangItem::Destruct, cx.body.span);
185        let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env);
186        let ocx = ObligationCtxt::new(&infcx);
187        ocx.register_obligation(Obligation::new(
188            cx.tcx,
189            ObligationCause::misc(cx.body.span, cx.def_id()),
190            param_env,
191            ty::Binder::dummy(ty::TraitRef::new(cx.tcx, destruct_def_id, [ty]))
192                .to_host_effect_clause(
193                    cx.tcx,
194                    match cx.const_kind() {
195                        rustc_hir::ConstContext::ConstFn => ty::BoundConstness::Maybe,
196                        rustc_hir::ConstContext::Static(_)
197                        | rustc_hir::ConstContext::Const { .. } => ty::BoundConstness::Const,
198                    },
199                ),
200        ));
201        !ocx.evaluate_obligations_error_on_ambiguity().no_errors()
202    }
203
204    fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
205        // As soon as an ADT has a destructor, then the drop becomes non-structural
206        // in its value since:
207        // 1. The destructor may have `[const]` bounds which are not present on the type.
208        //   Someone needs to check that those are satisfied.
209        //   While this could be instead satisfied by checking that the `[const] Drop`
210        //   impl holds (i.e. replicating part of the `in_any_value_of_ty` logic above),
211        //   even in this case, we have another problem, which is,
212        // 2. The destructor may *modify* the operand being dropped, so even if we
213        //   did recurse on the components of the operand, we may not be even dropping
214        //   the same values that were present before the custom destructor was invoked.
215        !adt.has_dtor(cx.tcx)
216    }
217}
218
219// FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
220
221/// Returns `true` if this `Rvalue` contains qualif `Q`.
222pub fn in_rvalue<'tcx, Q, F>(
223    cx: &ConstCx<'_, 'tcx>,
224    in_local: &mut F,
225    rvalue: &Rvalue<'tcx>,
226) -> bool
227where
228    Q: Qualif,
229    F: FnMut(Local) -> bool,
230{
231    match rvalue {
232        Rvalue::ThreadLocalRef(_) => Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)),
233
234        Rvalue::Discriminant(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
235
236        Rvalue::CopyForDeref(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
237
238        Rvalue::Use(operand, _)
239        | Rvalue::Repeat(operand, _)
240        | Rvalue::UnaryOp(_, operand)
241        | Rvalue::Cast(_, operand, _) => in_operand::<Q, _>(cx, in_local, operand),
242
243        Rvalue::BinaryOp(_, (lhs, rhs)) => {
244            in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
245        }
246
247        Rvalue::Ref(_, _, place) | Rvalue::RawPtr(_, place) => {
248            // Special-case reborrows to be more like a copy of the reference.
249            if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
250                let base_ty = place_base.ty(cx.body, cx.tcx).ty;
251                if let ty::Ref(..) = base_ty.kind() {
252                    return in_place::<Q, _>(cx, in_local, place_base);
253                }
254            }
255
256            in_place::<Q, _>(cx, in_local, place.as_ref())
257        }
258
259        Rvalue::Reborrow(_, _, place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
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::PhantomDeref
297            | ProjectionElem::Field(_, _)
298            | ProjectionElem::OpaqueCast(_)
299            | ProjectionElem::ConstantIndex { .. }
300            | ProjectionElem::Subslice { .. }
301            | ProjectionElem::Downcast(_, _)
302            | ProjectionElem::Index(_)
303            | ProjectionElem::UnwrapUnsafeBinder(_) => {}
304        }
305
306        let base_ty = place_base.ty(cx.body, cx.tcx);
307        let proj_ty = base_ty.projection_ty(cx.tcx, elem).ty;
308        if !Q::in_any_value_of_ty(cx, proj_ty) {
309            return false;
310        }
311
312        // `Deref` currently unconditionally "qualifies" if `in_any_value_of_ty` returns true,
313        // i.e., we treat all qualifs as non-structural for deref projections. Generally,
314        // we can say very little about `*ptr` even if we know that `ptr` satisfies all
315        // sorts of properties.
316        if elem == ProjectionElem::Deref {
317            // We have to assume that this qualifies.
318            return true;
319        }
320
321        place = place_base;
322    }
323
324    if !place.projection.is_empty() {
    ::core::panicking::panic("assertion failed: place.projection.is_empty()")
};assert!(place.projection.is_empty());
325    in_local(place.local)
326}
327
328/// Returns `true` if this `Operand` contains qualif `Q`.
329pub fn in_operand<'tcx, Q, F>(
330    cx: &ConstCx<'_, 'tcx>,
331    in_local: &mut F,
332    operand: &Operand<'tcx>,
333) -> bool
334where
335    Q: Qualif,
336    F: FnMut(Local) -> bool,
337{
338    let constant = match operand {
339        Operand::Copy(place) | Operand::Move(place) => {
340            return in_place::<Q, _>(cx, in_local, place.as_ref());
341        }
342        Operand::RuntimeChecks(_) => return Q::in_any_value_of_ty(cx, cx.tcx.types.bool),
343
344        Operand::Constant(c) => c,
345    };
346
347    // Check the qualifs of the value of `const` items.
348    let uneval = match constant.const_ {
349        Const::Ty(_, ct) => match ct.kind() {
350            ty::ConstKind::Param(_) | ty::ConstKind::Error(_) => None,
351            // Alias consts in MIR bodies don't have associated MIR (e.g. `type const`).
352            ty::ConstKind::Alias(_, _) => None,
353            // FIXME(mgca): Investigate whether using `None` for `ConstKind::Value` is overly
354            // strict, and if instead we should be doing some kind of value-based analysis.
355            ty::ConstKind::Value(_) => None,
356            _ => bug_impl(None,
    format_args!("expected ConstKind::Param, ConstKind::Value, ConstKind::Alias, or ConstKind::Error here, found {0:?}",
        ct), Location::caller())bug!(
357                "expected ConstKind::Param, ConstKind::Value, ConstKind::Alias, or ConstKind::Error here, found {:?}",
358                ct
359            ),
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        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);
370
371        // Don't peak inside trait associated constants.
372        if promoted.is_none() && cx.tcx.trait_of_assoc(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}