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::attrs::lang_items::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;
4950/// Whether this `Qualif` might be evaluated after the promotion and can encounter a promoted.
51const ALLOW_PROMOTED: bool;
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";
82const IS_CLEARED_ON_MOVE: bool = false;
83const ALLOW_PROMOTED: bool = false;
8485fn in_qualifs(qualifs: &ConstQualifs) -> bool {
86qualifs.has_mut_interior
87 }
8889fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
90// Avoid selecting for simple cases, such as builtin types.
91if ty.is_trivially_freeze() {
92return false;
93 }
9495// Avoid selecting for `UnsafeCell` either.
96if ty.ty_adt_def().is_some_and(|adt| adt.is_unsafe_cell()) {
97return true;
98 }
99100// 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.
104let freeze_def_id = cx.tcx.require_lang_item(LangItem::Freeze, cx.body.span);
105let did = cx.body.source.def_id().expect_local();
106107let typing_env = if cx.tcx.use_typing_mode_post_typeck_until_borrowck() {
108cx.typing_env
109 } else {
110 ty::TypingEnv::new(cx.typing_env.param_env, TypingMode::analysis_in_body(cx.tcx, did))
111 };
112113let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(typing_env);
114let ocx = ObligationCtxt::new(&infcx);
115let obligation = Obligation::new(
116cx.tcx,
117ObligationCause::dummy_with_span(cx.body.span),
118param_env,
119 ty::TraitRef::new(cx.tcx, freeze_def_id, [ty::GenericArg::from(ty)]),
120 );
121ocx.register_obligation(obligation);
122let errors = ocx.evaluate_obligations_error_on_ambiguity();
123 !errors.no_errors()
124 }
125126fn 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}
132133/// 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;
139140impl Qualiffor NeedsDrop {
141const ANALYSIS_NAME: &'static str = "flow_needs_drop";
142const IS_CLEARED_ON_MOVE: bool = true;
143const ALLOW_PROMOTED: bool = true;
144145fn in_qualifs(qualifs: &ConstQualifs) -> bool {
146qualifs.needs_drop
147 }
148149fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
150ty.needs_drop(cx.tcx, cx.typing_env)
151 }
152153fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
154 !adt.has_dtor(cx.tcx)
155 }
156}
157158/// 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;
161162impl Qualiffor NeedsNonConstDrop {
163const ANALYSIS_NAME: &'static str = "flow_needs_nonconst_drop";
164const IS_CLEARED_ON_MOVE: bool = true;
165const ALLOW_PROMOTED: bool = true;
166167fn in_qualifs(qualifs: &ConstQualifs) -> bool {
168qualifs.needs_non_const_drop
169 }
170171{}
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/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_const_eval/src/check_consts/qualifs.rs"),
::tracing_core::__macro_support::Option::Some(171u32),
::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/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_const_eval/src/check_consts/qualifs.rs:171",
"rustc_const_eval::check_consts::qualifs",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_const_eval/src/check_consts/qualifs.rs"),
::tracing_core::__macro_support::Option::Some(171u32),
::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)]172fn 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`.
174if !ty.needs_drop(cx.tcx, cx.typing_env) {
175return false;
176 }
177178// 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.
183let destruct_def_id = cx.tcx.require_lang_item(LangItem::Destruct, cx.body.span);
184let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env);
185let 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,
193match 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.evaluate_obligations_error_on_ambiguity().no_errors()
201 }
202203fn 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}
217218// FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
219220/// 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) -> bool226where
227Q: Qualif,
228 F: FnMut(Local) -> bool,
229{
230match rvalue {
231 Rvalue::ThreadLocalRef(_) => Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)),
232233 Rvalue::Discriminant(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
234235 Rvalue::CopyForDeref(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
236237 Rvalue::Use(operand, _)
238 | Rvalue::Repeat(operand, _)
239 | Rvalue::UnaryOp(_, operand)
240 | Rvalue::Cast(_, operand, _) => in_operand::<Q, _>(cx, in_local, operand),
241242 Rvalue::BinaryOp(_, (lhs, rhs)) => {
243in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
244 }
245246 Rvalue::Ref(_, _, place) | Rvalue::RawPtr(_, place) => {
247// Special-case reborrows to be more like a copy of the reference.
248if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
249let base_ty = place_base.ty(cx.body, cx.tcx).ty;
250if let ty::Ref(..) = base_ty.kind() {
251return in_place::<Q, _>(cx, in_local, place_base);
252 }
253 }
254255in_place::<Q, _>(cx, in_local, place.as_ref())
256 }
257258 Rvalue::Reborrow(_, _, place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
259260 Rvalue::WrapUnsafeBinder(op, _) => in_operand::<Q, _>(cx, in_local, op),
261262 Rvalue::Aggregate(kind, operands) => {
263// Return early if we know that the struct or enum being constructed is always
264 // qualified.
265if let AggregateKind::Adt(adt_did, ..) = **kind {
266let def = cx.tcx.adt_def(adt_did);
267// Don't do any value-based reasoning for unions.
268 // Also, if the ADT is not structural in its fields,
269 // then we cannot recurse on its fields. Instead,
270 // we fall back to checking the qualif for *any* value
271 // of the ADT.
272if def.is_union() || !Q::is_structural_in_adt_value(cx, def) {
273return Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx));
274 }
275 }
276277// Otherwise, proceed structurally...
278operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o))
279 }
280 }
281}
282283/// Returns `true` if this `Place` contains qualif `Q`.
284pub fn in_place<'tcx, Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool285where
286Q: Qualif,
287 F: FnMut(Local) -> bool,
288{
289let mut place = place;
290while let Some((place_base, elem)) = place.last_projection() {
291match elem {
292 ProjectionElem::Index(index) if in_local(index) => return true,
293294 ProjectionElem::Deref
295 | ProjectionElem::PhantomDeref
296 | ProjectionElem::Field(_, _)
297 | ProjectionElem::OpaqueCast(_)
298 | ProjectionElem::ConstantIndex { .. }
299 | ProjectionElem::Subslice { .. }
300 | ProjectionElem::Downcast(_, _)
301 | ProjectionElem::Index(_)
302 | ProjectionElem::UnwrapUnsafeBinder(_) => {}
303 }
304305let base_ty = place_base.ty(cx.body, cx.tcx);
306let proj_ty = base_ty.projection_ty(cx.tcx, elem).ty;
307if !Q::in_any_value_of_ty(cx, proj_ty) {
308return false;
309 }
310311// `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.
315if elem == ProjectionElem::Deref {
316// We have to assume that this qualifies.
317return true;
318 }
319320 place = place_base;
321 }
322323if !place.projection.is_empty() {
::core::panicking::panic("assertion failed: place.projection.is_empty()")
};assert!(place.projection.is_empty());
324in_local(place.local)
325}
326327/// 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) -> bool333where
334Q: Qualif,
335 F: FnMut(Local) -> bool,
336{
337let constant = match operand {
338 Operand::Copy(place) | Operand::Move(place) => {
339return 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),
342343 Operand::Constant(c) => c,
344 };
345346// Check the qualifs of the value of `const` items.
347let uneval = match constant.const_ {
348 Const::Ty(_, ct) => match ct.kind() {
349 ty::ConstKind::Param(_) | ty::ConstKind::Error(_) => None,
350// Alias consts in MIR bodies don't have associated MIR (e.g. `type const`).
351ty::ConstKind::Alias(_, _) => None,
352// FIXME(mgca): Investigate whether using `None` for `ConstKind::Value` is overly
353 // strict, and if instead we should be doing some kind of value-based analysis.
354ty::ConstKind::Value(_) => None,
355_ => ::rustc_middle::util::bug::bug_fmt(format_args!("expected ConstKind::Param, ConstKind::Value, ConstKind::Alias, or ConstKind::Error here, found {0:?}",
ct))bug!(
356"expected ConstKind::Param, ConstKind::Value, ConstKind::Alias, or ConstKind::Error here, found {:?}",
357 ct
358 ),
359 },
360 Const::Unevaluated(uv, _) => Some(uv),
361 Const::Val(..) => None,
362 };
363364if let Some(mir::UnevaluatedConst { def, args: _, promoted }) = uneval {
365// Use qualifs of the type for the promoted. Promoteds in MIR body should be possible
366 // only for `NeedsNonConstDrop` with precise drop checking. This is the only const
367 // check performed after the promotion. Verify that with an assertion.
368if !(promoted.is_none() || Q::ALLOW_PROMOTED) {
::core::panicking::panic("assertion failed: promoted.is_none() || Q::ALLOW_PROMOTED")
};assert!(promoted.is_none() || Q::ALLOW_PROMOTED);
369370// Don't peak inside trait associated constants.
371if promoted.is_none() && cx.tcx.trait_of_assoc(def).is_none() {
372let qualifs = cx.tcx.at(constant.span).mir_const_qualif(def);
373374if !Q::in_qualifs(&qualifs) {
375return false;
376 }
377378// Just in case the type is more specific than
379 // the definition, e.g., impl associated const
380 // with type parameters, take it into account.
381}
382 }
383384// Otherwise use the qualifs of the type.
385Q::in_any_value_of_ty(cx, constant.const_.ty())
386}