1 //! Structural const qualification.
3 //! See the `Qualif` trait for more info.
5 use rustc_errors::ErrorReported;
6 use rustc_middle::mir::*;
7 use rustc_middle::ty::{self, subst::SubstsRef, AdtDef, Ty};
8 use rustc_span::DUMMY_SP;
9 use rustc_trait_selection::traits;
13 pub fn in_any_value_of_ty(
14 cx: &ConstCx<'_, 'tcx>,
16 error_occured: Option<ErrorReported>,
19 has_mut_interior: HasMutInterior::in_any_value_of_ty(cx, ty),
20 needs_drop: NeedsDrop::in_any_value_of_ty(cx, ty),
21 custom_eq: CustomEq::in_any_value_of_ty(cx, ty),
26 /// A "qualif"(-ication) is a way to look for something "bad" in the MIR that would disqualify some
27 /// code for promotion or prevent it from evaluating at compile time.
29 /// Normally, we would determine what qualifications apply to each type and error when an illegal
30 /// operation is performed on such a type. However, this was found to be too imprecise, especially
31 /// in the presence of `enum`s. If only a single variant of an enum has a certain qualification, we
32 /// needn't reject code unless it actually constructs and operates on the qualifed variant.
34 /// To accomplish this, const-checking and promotion use a value-based analysis (as opposed to a
35 /// type-based one). Qualifications propagate structurally across variables: If a local (or a
36 /// projection of a local) is assigned a qualifed value, that local itself becomes qualifed.
38 /// The name of the file used to debug the dataflow analysis that computes this qualif.
39 const ANALYSIS_NAME: &'static str;
41 /// Whether this `Qualif` is cleared when a local is moved from.
42 const IS_CLEARED_ON_MOVE: bool = false;
44 /// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`.
45 fn in_qualifs(qualifs: &ConstQualifs) -> bool;
47 /// Returns `true` if *any* value of the given type could possibly have this `Qualif`.
49 /// This function determines `Qualif`s when we cannot do a value-based analysis. Since qualif
50 /// propagation is context-insenstive, this includes function arguments and values returned
51 /// from a call to another function.
53 /// It also determines the `Qualif`s for primitive types.
54 fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool;
56 /// Returns `true` if this `Qualif` is inherent to the given struct or enum.
58 /// By default, `Qualif`s propagate into ADTs in a structural way: An ADT only becomes
59 /// qualified if part of it is assigned a value with that `Qualif`. However, some ADTs *always*
60 /// have a certain `Qualif`, regardless of whether their fields have it. For example, a type
61 /// with a custom `Drop` impl is inherently `NeedsDrop`.
63 /// Returning `true` for `in_adt_inherently` but `false` for `in_any_value_of_ty` is unsound.
65 cx: &ConstCx<'_, 'tcx>,
67 substs: SubstsRef<'tcx>,
71 /// Constant containing interior mutability (`UnsafeCell<T>`).
72 /// This must be ruled out to make sure that evaluating the constant at compile-time
73 /// and at *any point* during the run-time would produce the same result. In particular,
74 /// promotion of temporaries must not change program behavior; if the promoted could be
75 /// written to, that would be a problem.
76 pub struct HasMutInterior;
78 impl Qualif for HasMutInterior {
79 const ANALYSIS_NAME: &'static str = "flow_has_mut_interior";
81 fn in_qualifs(qualifs: &ConstQualifs) -> bool {
82 qualifs.has_mut_interior
85 fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
86 !ty.is_freeze(cx.tcx.at(DUMMY_SP), cx.param_env)
89 fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool {
90 // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently.
91 // It arises structurally for all other types.
92 Some(adt.did) == cx.tcx.lang_items().unsafe_cell_type()
96 /// Constant containing an ADT that implements `Drop`.
97 /// This must be ruled out (a) because we cannot run `Drop` during compile-time
98 /// as that might not be a `const fn`, and (b) because implicit promotion would
99 /// remove side-effects that occur as part of dropping that value.
100 pub struct NeedsDrop;
102 impl Qualif for NeedsDrop {
103 const ANALYSIS_NAME: &'static str = "flow_needs_drop";
104 const IS_CLEARED_ON_MOVE: bool = true;
106 fn in_qualifs(qualifs: &ConstQualifs) -> bool {
110 fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
111 ty.needs_drop(cx.tcx, cx.param_env)
114 fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool {
119 /// A constant that cannot be used as part of a pattern in a `match` expression.
122 impl Qualif for CustomEq {
123 const ANALYSIS_NAME: &'static str = "flow_custom_eq";
125 fn in_qualifs(qualifs: &ConstQualifs) -> bool {
129 fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
130 // If *any* component of a composite data type does not implement `Structural{Partial,}Eq`,
131 // we know that at least some values of that type are not structural-match. I say "some"
132 // because that component may be part of an enum variant (e.g.,
133 // `Option::<NonStructuralMatchTy>::Some`), in which case some values of this type may be
134 // structural-match (`Option::None`).
135 let id = cx.tcx.hir().local_def_id_to_hir_id(cx.def_id());
136 traits::search_for_structural_match_violation(id, cx.body.span, cx.tcx, ty).is_some()
139 fn in_adt_inherently(
140 cx: &ConstCx<'_, 'tcx>,
142 substs: SubstsRef<'tcx>,
144 let ty = cx.tcx.mk_ty(ty::Adt(adt, substs));
145 !ty.is_structural_eq_shallow(cx.tcx)
149 // FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
151 /// Returns `true` if this `Rvalue` contains qualif `Q`.
152 pub fn in_rvalue<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, rvalue: &Rvalue<'tcx>) -> bool
155 F: FnMut(Local) -> bool,
158 Rvalue::ThreadLocalRef(_) | Rvalue::NullaryOp(..) => {
159 Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx))
162 Rvalue::Discriminant(place) | Rvalue::Len(place) => {
163 in_place::<Q, _>(cx, in_local, place.as_ref())
167 | Rvalue::Repeat(operand, _)
168 | Rvalue::UnaryOp(_, operand)
169 | Rvalue::Cast(_, operand, _) => in_operand::<Q, _>(cx, in_local, operand),
171 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
172 in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
175 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
176 // Special-case reborrows to be more like a copy of the reference.
177 if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
178 let base_ty = place_base.ty(cx.body, cx.tcx).ty;
179 if let ty::Ref(..) = base_ty.kind() {
180 return in_place::<Q, _>(cx, in_local, place_base);
184 in_place::<Q, _>(cx, in_local, place.as_ref())
187 Rvalue::Aggregate(kind, operands) => {
188 // Return early if we know that the struct or enum being constructed is always
190 if let AggregateKind::Adt(def, _, substs, ..) = **kind {
191 if Q::in_adt_inherently(cx, def, substs) {
196 // Otherwise, proceed structurally...
197 operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o))
202 /// Returns `true` if this `Place` contains qualif `Q`.
203 pub fn in_place<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool
206 F: FnMut(Local) -> bool,
208 let mut place = place;
209 while let Some((place_base, elem)) = place.last_projection() {
211 ProjectionElem::Index(index) if in_local(index) => return true,
213 ProjectionElem::Deref
214 | ProjectionElem::Field(_, _)
215 | ProjectionElem::ConstantIndex { .. }
216 | ProjectionElem::Subslice { .. }
217 | ProjectionElem::Downcast(_, _)
218 | ProjectionElem::Index(_) => {}
221 let base_ty = place_base.ty(cx.body, cx.tcx);
222 let proj_ty = base_ty.projection_ty(cx.tcx, elem).ty;
223 if !Q::in_any_value_of_ty(cx, proj_ty) {
230 assert!(place.projection.is_empty());
231 in_local(place.local)
234 /// Returns `true` if this `Operand` contains qualif `Q`.
235 pub fn in_operand<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, operand: &Operand<'tcx>) -> bool
238 F: FnMut(Local) -> bool,
240 let constant = match operand {
241 Operand::Copy(place) | Operand::Move(place) => {
242 return in_place::<Q, _>(cx, in_local, place.as_ref());
245 Operand::Constant(c) => c,
248 // Check the qualifs of the value of `const` items.
249 if let ty::ConstKind::Unevaluated(def, _, None) = constant.literal.val {
250 // Don't peek inside trait associated constants.
251 if cx.tcx.trait_of_item(def.did).is_none() {
252 let qualifs = if let Some((did, param_did)) = def.as_const_arg() {
253 cx.tcx.at(constant.span).mir_const_qualif_const_arg((did, param_did))
255 cx.tcx.at(constant.span).mir_const_qualif(def.did)
258 if !Q::in_qualifs(&qualifs) {
262 // Just in case the type is more specific than
263 // the definition, e.g., impl associated const
264 // with type parameters, take it into account.
267 // Otherwise use the qualifs of the type.
268 Q::in_any_value_of_ty(cx, constant.literal.ty)