]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs
Rollup merge of #102146 - notriddle:notriddle/sidebar-jank, r=GuillaumeGomez
[rust.git] / compiler / rustc_const_eval / src / transform / check_consts / qualifs.rs
1 //! Structural const qualification.
2 //!
3 //! See the `Qualif` trait for more info.
4
5 use rustc_errors::ErrorGuaranteed;
6 use rustc_hir::LangItem;
7 use rustc_infer::infer::TyCtxtInferExt;
8 use rustc_middle::mir;
9 use rustc_middle::mir::*;
10 use rustc_middle::ty::{self, subst::SubstsRef, AdtDef, Ty};
11 use rustc_span::DUMMY_SP;
12 use rustc_trait_selection::traits::{
13     self, ImplSource, Obligation, ObligationCause, SelectionContext,
14 };
15
16 use super::ConstCx;
17
18 pub fn in_any_value_of_ty<'tcx>(
19     cx: &ConstCx<'_, 'tcx>,
20     ty: Ty<'tcx>,
21     tainted_by_errors: Option<ErrorGuaranteed>,
22 ) -> ConstQualifs {
23     ConstQualifs {
24         has_mut_interior: HasMutInterior::in_any_value_of_ty(cx, ty),
25         needs_drop: NeedsDrop::in_any_value_of_ty(cx, ty),
26         needs_non_const_drop: NeedsNonConstDrop::in_any_value_of_ty(cx, ty),
27         custom_eq: CustomEq::in_any_value_of_ty(cx, ty),
28         tainted_by_errors,
29     }
30 }
31
32 /// 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.
43 pub trait Qualif {
44     /// The name of the file used to debug the dataflow analysis that computes this qualif.
45     const ANALYSIS_NAME: &'static str;
46
47     /// Whether this `Qualif` is cleared when a local is moved from.
48     const IS_CLEARED_ON_MOVE: bool = false;
49
50     /// Whether this `Qualif` might be evaluated after the promotion and can encounter a promoted.
51     const ALLOW_PROMOTED: bool = false;
52
53     /// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`.
54     fn in_qualifs(qualifs: &ConstQualifs) -> bool;
55
56     /// 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.
63     fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool;
64
65     /// Returns `true` if this `Qualif` is inherent to the given struct or enum.
66     ///
67     /// By default, `Qualif`s propagate into ADTs in a structural way: An ADT only becomes
68     /// qualified if part of it is assigned a value with that `Qualif`. However, some ADTs *always*
69     /// have a certain `Qualif`, regardless of whether their fields have it. For example, a type
70     /// with a custom `Drop` impl is inherently `NeedsDrop`.
71     ///
72     /// Returning `true` for `in_adt_inherently` but `false` for `in_any_value_of_ty` is unsound.
73     fn in_adt_inherently<'tcx>(
74         cx: &ConstCx<'_, 'tcx>,
75         adt: AdtDef<'tcx>,
76         substs: SubstsRef<'tcx>,
77     ) -> bool;
78 }
79
80 /// Constant containing interior mutability (`UnsafeCell<T>`).
81 /// This must be ruled out to make sure that evaluating the constant at compile-time
82 /// and at *any point* during the run-time would produce the same result. In particular,
83 /// promotion of temporaries must not change program behavior; if the promoted could be
84 /// written to, that would be a problem.
85 pub struct HasMutInterior;
86
87 impl Qualif for HasMutInterior {
88     const ANALYSIS_NAME: &'static str = "flow_has_mut_interior";
89
90     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
91         qualifs.has_mut_interior
92     }
93
94     fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
95         !ty.is_freeze(cx.tcx.at(DUMMY_SP), cx.param_env)
96     }
97
98     fn in_adt_inherently<'tcx>(
99         _cx: &ConstCx<'_, 'tcx>,
100         adt: AdtDef<'tcx>,
101         _: SubstsRef<'tcx>,
102     ) -> bool {
103         // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently.
104         // It arises structurally for all other types.
105         adt.is_unsafe_cell()
106     }
107 }
108
109 /// Constant containing an ADT that implements `Drop`.
110 /// This must be ruled out because implicit promotion would remove side-effects
111 /// that occur as part of dropping that value. N.B., the implicit promotion has
112 /// to reject const Drop implementations because even if side-effects are ruled
113 /// out through other means, the execution of the drop could diverge.
114 pub struct NeedsDrop;
115
116 impl Qualif for NeedsDrop {
117     const ANALYSIS_NAME: &'static str = "flow_needs_drop";
118     const IS_CLEARED_ON_MOVE: bool = true;
119
120     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
121         qualifs.needs_drop
122     }
123
124     fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
125         ty.needs_drop(cx.tcx, cx.param_env)
126     }
127
128     fn in_adt_inherently<'tcx>(
129         cx: &ConstCx<'_, 'tcx>,
130         adt: AdtDef<'tcx>,
131         _: SubstsRef<'tcx>,
132     ) -> bool {
133         adt.has_dtor(cx.tcx)
134     }
135 }
136
137 /// Constant containing an ADT that implements non-const `Drop`.
138 /// This must be ruled out because we cannot run `Drop` during compile-time.
139 pub struct NeedsNonConstDrop;
140
141 impl Qualif for NeedsNonConstDrop {
142     const ANALYSIS_NAME: &'static str = "flow_needs_nonconst_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_non_const_drop
148     }
149
150     fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
151         // Avoid selecting for simple cases, such as builtin types.
152         if ty::util::is_trivially_const_drop(ty) {
153             return false;
154         }
155
156         let destruct = cx.tcx.require_lang_item(LangItem::Destruct, None);
157
158         let obligation = Obligation::new(
159             ObligationCause::dummy(),
160             cx.param_env,
161             ty::Binder::dummy(ty::TraitPredicate {
162                 trait_ref: ty::TraitRef {
163                     def_id: destruct,
164                     substs: cx.tcx.mk_substs_trait(ty, &[]),
165                 },
166                 constness: ty::BoundConstness::ConstIfConst,
167                 polarity: ty::ImplPolarity::Positive,
168             }),
169         );
170
171         cx.tcx.infer_ctxt().enter(|infcx| {
172             let mut selcx = SelectionContext::new(&infcx);
173             let Some(impl_src) = selcx.select(&obligation).ok().flatten() else {
174                 // If we couldn't select a const destruct candidate, then it's bad
175                 return true;
176             };
177
178             if !matches!(
179                 impl_src,
180                 ImplSource::ConstDestruct(_)
181                     | ImplSource::Param(_, ty::BoundConstness::ConstIfConst)
182             ) {
183                 // If our const destruct candidate is not ConstDestruct or implied by the param env,
184                 // then it's bad
185                 return true;
186             }
187
188             if impl_src.borrow_nested_obligations().is_empty() {
189                 return false;
190             }
191
192             // If we had any errors, then it's bad
193             !traits::fully_solve_obligations(&infcx, impl_src.nested_obligations()).is_empty()
194         })
195     }
196
197     fn in_adt_inherently<'tcx>(
198         cx: &ConstCx<'_, 'tcx>,
199         adt: AdtDef<'tcx>,
200         _: SubstsRef<'tcx>,
201     ) -> bool {
202         adt.has_non_const_dtor(cx.tcx)
203     }
204 }
205
206 /// A constant that cannot be used as part of a pattern in a `match` expression.
207 pub struct CustomEq;
208
209 impl Qualif for CustomEq {
210     const ANALYSIS_NAME: &'static str = "flow_custom_eq";
211
212     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
213         qualifs.custom_eq
214     }
215
216     fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
217         // If *any* component of a composite data type does not implement `Structural{Partial,}Eq`,
218         // we know that at least some values of that type are not structural-match. I say "some"
219         // because that component may be part of an enum variant (e.g.,
220         // `Option::<NonStructuralMatchTy>::Some`), in which case some values of this type may be
221         // structural-match (`Option::None`).
222         traits::search_for_structural_match_violation(cx.body.span, cx.tcx, ty).is_some()
223     }
224
225     fn in_adt_inherently<'tcx>(
226         cx: &ConstCx<'_, 'tcx>,
227         adt: AdtDef<'tcx>,
228         substs: SubstsRef<'tcx>,
229     ) -> bool {
230         let ty = cx.tcx.mk_ty(ty::Adt(adt, substs));
231         !ty.is_structural_eq_shallow(cx.tcx)
232     }
233 }
234
235 // FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
236
237 /// Returns `true` if this `Rvalue` contains qualif `Q`.
238 pub fn in_rvalue<'tcx, Q, F>(
239     cx: &ConstCx<'_, 'tcx>,
240     in_local: &mut F,
241     rvalue: &Rvalue<'tcx>,
242 ) -> bool
243 where
244     Q: Qualif,
245     F: FnMut(Local) -> bool,
246 {
247     match rvalue {
248         Rvalue::ThreadLocalRef(_) | Rvalue::NullaryOp(..) => {
249             Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx))
250         }
251
252         Rvalue::Discriminant(place) | Rvalue::Len(place) => {
253             in_place::<Q, _>(cx, in_local, place.as_ref())
254         }
255
256         Rvalue::CopyForDeref(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
257
258         Rvalue::Use(operand)
259         | Rvalue::Repeat(operand, _)
260         | Rvalue::UnaryOp(_, operand)
261         | Rvalue::Cast(_, operand, _)
262         | Rvalue::ShallowInitBox(operand, _) => in_operand::<Q, _>(cx, in_local, operand),
263
264         Rvalue::BinaryOp(_, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(_, box (lhs, rhs)) => {
265             in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
266         }
267
268         Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
269             // Special-case reborrows to be more like a copy of the reference.
270             if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
271                 let base_ty = place_base.ty(cx.body, cx.tcx).ty;
272                 if let ty::Ref(..) = base_ty.kind() {
273                     return in_place::<Q, _>(cx, in_local, place_base);
274                 }
275             }
276
277             in_place::<Q, _>(cx, in_local, place.as_ref())
278         }
279
280         Rvalue::Aggregate(kind, operands) => {
281             // Return early if we know that the struct or enum being constructed is always
282             // qualified.
283             if let AggregateKind::Adt(adt_did, _, substs, ..) = **kind {
284                 let def = cx.tcx.adt_def(adt_did);
285                 if Q::in_adt_inherently(cx, def, substs) {
286                     return true;
287                 }
288                 if def.is_union() && Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) {
289                     return true;
290                 }
291             }
292
293             // Otherwise, proceed structurally...
294             operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o))
295         }
296     }
297 }
298
299 /// Returns `true` if this `Place` contains qualif `Q`.
300 pub fn in_place<'tcx, Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool
301 where
302     Q: Qualif,
303     F: FnMut(Local) -> bool,
304 {
305     let mut place = place;
306     while let Some((place_base, elem)) = place.last_projection() {
307         match elem {
308             ProjectionElem::Index(index) if in_local(index) => return true,
309
310             ProjectionElem::Deref
311             | ProjectionElem::Field(_, _)
312             | ProjectionElem::OpaqueCast(_)
313             | ProjectionElem::ConstantIndex { .. }
314             | ProjectionElem::Subslice { .. }
315             | ProjectionElem::Downcast(_, _)
316             | ProjectionElem::Index(_) => {}
317         }
318
319         let base_ty = place_base.ty(cx.body, cx.tcx);
320         let proj_ty = base_ty.projection_ty(cx.tcx, elem).ty;
321         if !Q::in_any_value_of_ty(cx, proj_ty) {
322             return false;
323         }
324
325         place = place_base;
326     }
327
328     assert!(place.projection.is_empty());
329     in_local(place.local)
330 }
331
332 /// Returns `true` if this `Operand` contains qualif `Q`.
333 pub fn in_operand<'tcx, Q, F>(
334     cx: &ConstCx<'_, 'tcx>,
335     in_local: &mut F,
336     operand: &Operand<'tcx>,
337 ) -> bool
338 where
339     Q: Qualif,
340     F: FnMut(Local) -> bool,
341 {
342     let constant = match operand {
343         Operand::Copy(place) | Operand::Move(place) => {
344             return in_place::<Q, _>(cx, in_local, place.as_ref());
345         }
346
347         Operand::Constant(c) => c,
348     };
349
350     // Check the qualifs of the value of `const` items.
351     // FIXME(valtrees): check whether const qualifs should behave the same
352     // way for type and mir constants.
353     let uneval = match constant.literal {
354         ConstantKind::Ty(ct) if matches!(ct.kind(), ty::ConstKind::Param(_)) => None,
355         ConstantKind::Ty(c) => bug!("expected ConstKind::Param here, found {:?}", c),
356         ConstantKind::Unevaluated(uv, _) => Some(uv),
357         ConstantKind::Val(..) => None,
358     };
359
360     if let Some(mir::UnevaluatedConst { def, substs: _, promoted }) = uneval {
361         // Use qualifs of the type for the promoted. Promoteds in MIR body should be possible
362         // only for `NeedsNonConstDrop` with precise drop checking. This is the only const
363         // check performed after the promotion. Verify that with an assertion.
364         assert!(promoted.is_none() || Q::ALLOW_PROMOTED);
365
366         // Don't peek inside trait associated constants.
367         if promoted.is_none() && cx.tcx.trait_of_item(def.did).is_none() {
368             assert_eq!(def.const_param_did, None, "expected associated const: {def:?}");
369             let qualifs = cx.tcx.at(constant.span).mir_const_qualif(def.did);
370
371             if !Q::in_qualifs(&qualifs) {
372                 return false;
373             }
374
375             // Just in case the type is more specific than
376             // the definition, e.g., impl associated const
377             // with type parameters, take it into account.
378         }
379     }
380
381     // Otherwise use the qualifs of the type.
382     Q::in_any_value_of_ty(cx, constant.literal.ty())
383 }