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::mir::*;
13use rustc_middle::ty::{self, AdtDef, Ty, TypingMode};
14use rustc_span::bug;
15use rustc_trait_selection::traits::{Obligation, ObligationCause, ObligationCtxt};
16use tracing::instrument;
1718use super::ConstCx;
1920pub fn in_any_value_of_ty<'tcx>(
21 cx: &ConstCx<'_, 'tcx>,
22 ty: Ty<'tcx>,
23 tainted_by_errors: Option<ErrorGuaranteed>,
24) -> ConstQualifs {
25ConstQualifs {
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),
29tainted_by_errors,
30 }
31}
3233/// 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.
46const ANALYSIS_NAME: &'static str;
4748/// Whether this `Qualif` is cleared when a local is moved from.
49const IS_CLEARED_ON_MOVE: bool;
5051/// Whether this `Qualif` might be evaluated after the promotion and can encounter a promoted.
52const ALLOW_PROMOTED: bool;
5354/// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`.
55fn in_qualifs(qualifs: &ConstQualifs) -> bool;
5657/// 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.
64fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool;
6566/// 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.
71fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool;
72}
7374/// 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;
8081impl Qualiffor HasMutInterior {
82const ANALYSIS_NAME: &'static str = "flow_has_mut_interior";
83const IS_CLEARED_ON_MOVE: bool = false;
84const ALLOW_PROMOTED: bool = false;
8586fn in_qualifs(qualifs: &ConstQualifs) -> bool {
87qualifs.has_mut_interior
88 }
8990fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
91// Avoid selecting for simple cases, such as builtin types.
92if ty.is_trivially_freeze() {
93return false;
94 }
9596// Avoid selecting for `UnsafeCell` either.
97if ty.ty_adt_def().is_some_and(|adt| adt.is_unsafe_cell()) {
98return true;
99 }
100101// 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.
105let freeze_def_id = cx.tcx.require_lang_item(LangItem::Freeze, cx.body.span);
106let did = cx.body.source.def_id().expect_local();
107108let typing_env = if cx.tcx.use_typing_mode_post_typeck_until_borrowck() {
109cx.typing_env
110 } else {
111 ty::TypingEnv::new(cx.typing_env.param_env, TypingMode::analysis_in_body(cx.tcx, did))
112 };
113114let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(typing_env);
115let ocx = ObligationCtxt::new(&infcx);
116let obligation = Obligation::new(
117cx.tcx,
118ObligationCause::dummy_with_span(cx.body.span),
119param_env,
120 ty::TraitRef::new(cx.tcx, freeze_def_id, [ty::GenericArg::from(ty)]),
121 );
122ocx.register_obligation(obligation);
123let errors = ocx.evaluate_obligations_error_on_ambiguity();
124 !errors.no_errors()
125 }
126127fn 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}
133134/// 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;
140141impl Qualiffor NeedsDrop {
142const ANALYSIS_NAME: &'static str = "flow_needs_drop";
143const IS_CLEARED_ON_MOVE: bool = true;
144const ALLOW_PROMOTED: bool = true;
145146fn in_qualifs(qualifs: &ConstQualifs) -> bool {
147qualifs.needs_drop
148 }
149150fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
151ty.needs_drop(cx.tcx, cx.typing_env)
152 }
153154fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
155 !adt.has_dtor(cx.tcx)
156 }
157}
158159/// 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;
162163impl Qualiffor NeedsNonConstDrop {
164const ANALYSIS_NAME: &'static str = "flow_needs_nonconst_drop";
165const IS_CLEARED_ON_MOVE: bool = true;
166const ALLOW_PROMOTED: bool = true;
167168fn in_qualifs(qualifs: &ConstQualifs) -> bool {
169qualifs.needs_non_const_drop
170 }
171172{}
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)]173fn 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`.
175if !ty.needs_drop(cx.tcx, cx.typing_env) {
176return false;
177 }
178179// 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.
184let destruct_def_id = cx.tcx.require_lang_item(LangItem::Destruct, cx.body.span);
185let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env);
186let 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,
194match 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 }
203204fn 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}
218219// FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
220221/// 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) -> bool227where
228Q: Qualif,
229 F: FnMut(Local) -> bool,
230{
231match rvalue {
232 Rvalue::ThreadLocalRef(_) => Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)),
233234 Rvalue::Discriminant(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
235236 Rvalue::CopyForDeref(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
237238 Rvalue::Use(operand, _)
239 | Rvalue::Repeat(operand, _)
240 | Rvalue::UnaryOp(_, operand)
241 | Rvalue::Cast(_, operand, _) => in_operand::<Q, _>(cx, in_local, operand),
242243 Rvalue::BinaryOp(_, (lhs, rhs)) => {
244in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
245 }
246247 Rvalue::Ref(_, _, place) | Rvalue::RawPtr(_, place) => {
248// Special-case reborrows to be more like a copy of the reference.
249if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
250let base_ty = place_base.ty(cx.body, cx.tcx).ty;
251if let ty::Ref(..) = base_ty.kind() {
252return in_place::<Q, _>(cx, in_local, place_base);
253 }
254 }
255256in_place::<Q, _>(cx, in_local, place.as_ref())
257 }
258259 Rvalue::Reborrow(_, _, place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
260261 Rvalue::WrapUnsafeBinder(op, _) => in_operand::<Q, _>(cx, in_local, op),
262263 Rvalue::Aggregate(kind, operands) => {
264// Return early if we know that the struct or enum being constructed is always
265 // qualified.
266if let AggregateKind::Adt(adt_did, ..) = **kind {
267let 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.
273if def.is_union() || !Q::is_structural_in_adt_value(cx, def) {
274return Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx));
275 }
276 }
277278// Otherwise, proceed structurally...
279operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o))
280 }
281 }
282}
283284/// 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>) -> bool286where
287Q: Qualif,
288 F: FnMut(Local) -> bool,
289{
290let mut place = place;
291while let Some((place_base, elem)) = place.last_projection() {
292match elem {
293 ProjectionElem::Index(index) if in_local(index) => return true,
294295 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 }
305306let base_ty = place_base.ty(cx.body, cx.tcx);
307let proj_ty = base_ty.projection_ty(cx.tcx, elem).ty;
308if !Q::in_any_value_of_ty(cx, proj_ty) {
309return false;
310 }
311312// `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.
316if elem == ProjectionElem::Deref {
317// We have to assume that this qualifies.
318return true;
319 }
320321 place = place_base;
322 }
323324if !place.projection.is_empty() {
::core::panicking::panic("assertion failed: place.projection.is_empty()")
};assert!(place.projection.is_empty());
325in_local(place.local)
326}
327328/// 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) -> bool334where
335Q: Qualif,
336 F: FnMut(Local) -> bool,
337{
338let constant = match operand {
339 Operand::Copy(place) | Operand::Move(place) => {
340return 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),
343344 Operand::Constant(c) => c,
345 };
346347// Check the qualifs of the value of `const` items.
348let 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`).
352ty::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.
355ty::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 };
364365if 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.
369if !(promoted.is_none() || Q::ALLOW_PROMOTED) {
::core::panicking::panic("assertion failed: promoted.is_none() || Q::ALLOW_PROMOTED")
};assert!(promoted.is_none() || Q::ALLOW_PROMOTED);
370371// Don't peak inside trait associated constants.
372if promoted.is_none() && cx.tcx.trait_of_assoc(def).is_none() {
373let qualifs = cx.tcx.at(constant.span).mir_const_qualif(def);
374375if !Q::in_qualifs(&qualifs) {
376return false;
377 }
378379// 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 }
384385// Otherwise use the qualifs of the type.
386Q::in_any_value_of_ty(cx, constant.const_.ty())
387}