1 //! Structural const qualification.
3 //! See the `Qualif` trait for more info.
5 use rustc_middle
::mir
::*;
6 use rustc_middle
::ty
::{self, subst::SubstsRef, AdtDef, Ty}
;
7 use rustc_span
::DUMMY_SP
;
8 use rustc_trait_selection
::traits
;
12 pub fn in_any_value_of_ty(cx
: &ConstCx
<'_
, 'tcx
>, ty
: Ty
<'tcx
>) -> ConstQualifs
{
14 has_mut_interior
: HasMutInterior
::in_any_value_of_ty(cx
, ty
),
15 needs_drop
: NeedsDrop
::in_any_value_of_ty(cx
, ty
),
16 custom_eq
: CustomEq
::in_any_value_of_ty(cx
, ty
),
20 /// A "qualif"(-ication) is a way to look for something "bad" in the MIR that would disqualify some
21 /// code for promotion or prevent it from evaluating at compile time.
23 /// Normally, we would determine what qualifications apply to each type and error when an illegal
24 /// operation is performed on such a type. However, this was found to be too imprecise, especially
25 /// in the presence of `enum`s. If only a single variant of an enum has a certain qualification, we
26 /// needn't reject code unless it actually constructs and operates on the qualifed variant.
28 /// To accomplish this, const-checking and promotion use a value-based analysis (as opposed to a
29 /// type-based one). Qualifications propagate structurally across variables: If a local (or a
30 /// projection of a local) is assigned a qualifed value, that local itself becomes qualifed.
32 /// The name of the file used to debug the dataflow analysis that computes this qualif.
33 const ANALYSIS_NAME
: &'
static str;
35 /// Whether this `Qualif` is cleared when a local is moved from.
36 const IS_CLEARED_ON_MOVE
: bool
= false;
38 /// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`.
39 fn in_qualifs(qualifs
: &ConstQualifs
) -> bool
;
41 /// Returns `true` if *any* value of the given type could possibly have this `Qualif`.
43 /// This function determines `Qualif`s when we cannot do a value-based analysis. Since qualif
44 /// propagation is context-insenstive, this includes function arguments and values returned
45 /// from a call to another function.
47 /// It also determines the `Qualif`s for primitive types.
48 fn in_any_value_of_ty(cx
: &ConstCx
<'_
, 'tcx
>, ty
: Ty
<'tcx
>) -> bool
;
50 /// Returns `true` if this `Qualif` is inherent to the given struct or enum.
52 /// By default, `Qualif`s propagate into ADTs in a structural way: An ADT only becomes
53 /// qualified if part of it is assigned a value with that `Qualif`. However, some ADTs *always*
54 /// have a certain `Qualif`, regardless of whether their fields have it. For example, a type
55 /// with a custom `Drop` impl is inherently `NeedsDrop`.
57 /// Returning `true` for `in_adt_inherently` but `false` for `in_any_value_of_ty` is unsound.
59 cx
: &ConstCx
<'_
, 'tcx
>,
61 substs
: SubstsRef
<'tcx
>,
65 /// Constant containing interior mutability (`UnsafeCell<T>`).
66 /// This must be ruled out to make sure that evaluating the constant at compile-time
67 /// and at *any point* during the run-time would produce the same result. In particular,
68 /// promotion of temporaries must not change program behavior; if the promoted could be
69 /// written to, that would be a problem.
70 pub struct HasMutInterior
;
72 impl Qualif
for HasMutInterior
{
73 const ANALYSIS_NAME
: &'
static str = "flow_has_mut_interior";
75 fn in_qualifs(qualifs
: &ConstQualifs
) -> bool
{
76 qualifs
.has_mut_interior
79 fn in_any_value_of_ty(cx
: &ConstCx
<'_
, 'tcx
>, ty
: Ty
<'tcx
>) -> bool
{
80 !ty
.is_freeze(cx
.tcx
.at(DUMMY_SP
), cx
.param_env
)
83 fn in_adt_inherently(cx
: &ConstCx
<'_
, 'tcx
>, adt
: &'tcx AdtDef
, _
: SubstsRef
<'tcx
>) -> bool
{
84 // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently.
85 // It arises structurally for all other types.
86 Some(adt
.did
) == cx
.tcx
.lang_items().unsafe_cell_type()
90 /// Constant containing an ADT that implements `Drop`.
91 /// This must be ruled out (a) because we cannot run `Drop` during compile-time
92 /// as that might not be a `const fn`, and (b) because implicit promotion would
93 /// remove side-effects that occur as part of dropping that value.
96 impl Qualif
for NeedsDrop
{
97 const ANALYSIS_NAME
: &'
static str = "flow_needs_drop";
98 const IS_CLEARED_ON_MOVE
: bool
= true;
100 fn in_qualifs(qualifs
: &ConstQualifs
) -> bool
{
104 fn in_any_value_of_ty(cx
: &ConstCx
<'_
, 'tcx
>, ty
: Ty
<'tcx
>) -> bool
{
105 ty
.needs_drop(cx
.tcx
, cx
.param_env
)
108 fn in_adt_inherently(cx
: &ConstCx
<'_
, 'tcx
>, adt
: &'tcx AdtDef
, _
: SubstsRef
<'tcx
>) -> bool
{
113 /// A constant that cannot be used as part of a pattern in a `match` expression.
116 impl Qualif
for CustomEq
{
117 const ANALYSIS_NAME
: &'
static str = "flow_custom_eq";
119 fn in_qualifs(qualifs
: &ConstQualifs
) -> bool
{
123 fn in_any_value_of_ty(cx
: &ConstCx
<'_
, 'tcx
>, ty
: Ty
<'tcx
>) -> bool
{
124 // If *any* component of a composite data type does not implement `Structural{Partial,}Eq`,
125 // we know that at least some values of that type are not structural-match. I say "some"
126 // because that component may be part of an enum variant (e.g.,
127 // `Option::<NonStructuralMatchTy>::Some`), in which case some values of this type may be
128 // structural-match (`Option::None`).
129 let id
= cx
.tcx
.hir().local_def_id_to_hir_id(cx
.def_id());
130 traits
::search_for_structural_match_violation(id
, cx
.body
.span
, cx
.tcx
, ty
).is_some()
133 fn in_adt_inherently(
134 cx
: &ConstCx
<'_
, 'tcx
>,
136 substs
: SubstsRef
<'tcx
>,
138 let ty
= cx
.tcx
.mk_ty(ty
::Adt(adt
, substs
));
139 !ty
.is_structural_eq_shallow(cx
.tcx
)
143 // FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
145 /// Returns `true` if this `Rvalue` contains qualif `Q`.
146 pub fn in_rvalue
<Q
, F
>(cx
: &ConstCx
<'_
, 'tcx
>, in_local
: &mut F
, rvalue
: &Rvalue
<'tcx
>) -> bool
149 F
: FnMut(Local
) -> bool
,
152 Rvalue
::ThreadLocalRef(_
) | Rvalue
::NullaryOp(..) => {
153 Q
::in_any_value_of_ty(cx
, rvalue
.ty(cx
.body
, cx
.tcx
))
156 Rvalue
::Discriminant(place
) | Rvalue
::Len(place
) => {
157 in_place
::<Q
, _
>(cx
, in_local
, place
.as_ref())
161 | Rvalue
::Repeat(operand
, _
)
162 | Rvalue
::UnaryOp(_
, operand
)
163 | Rvalue
::Cast(_
, operand
, _
) => in_operand
::<Q
, _
>(cx
, in_local
, operand
),
165 Rvalue
::BinaryOp(_
, lhs
, rhs
) | Rvalue
::CheckedBinaryOp(_
, lhs
, rhs
) => {
166 in_operand
::<Q
, _
>(cx
, in_local
, lhs
) || in_operand
::<Q
, _
>(cx
, in_local
, rhs
)
169 Rvalue
::Ref(_
, _
, place
) | Rvalue
::AddressOf(_
, place
) => {
170 // Special-case reborrows to be more like a copy of the reference.
171 if let &[ref proj_base @
.., ProjectionElem
::Deref
] = place
.projection
.as_ref() {
172 let base_ty
= Place
::ty_from(place
.local
, proj_base
, cx
.body
, cx
.tcx
).ty
;
173 if let ty
::Ref(..) = base_ty
.kind() {
174 return in_place
::<Q
, _
>(
177 PlaceRef { local: place.local, projection: proj_base }
,
182 in_place
::<Q
, _
>(cx
, in_local
, place
.as_ref())
185 Rvalue
::Aggregate(kind
, operands
) => {
186 // Return early if we know that the struct or enum being constructed is always
188 if let AggregateKind
::Adt(def
, _
, substs
, ..) = **kind
{
189 if Q
::in_adt_inherently(cx
, def
, substs
) {
194 // Otherwise, proceed structurally...
195 operands
.iter().any(|o
| in_operand
::<Q
, _
>(cx
, in_local
, o
))
200 /// Returns `true` if this `Place` contains qualif `Q`.
201 pub fn in_place
<Q
, F
>(cx
: &ConstCx
<'_
, 'tcx
>, in_local
: &mut F
, place
: PlaceRef
<'tcx
>) -> bool
204 F
: FnMut(Local
) -> bool
,
206 let mut projection
= place
.projection
;
207 while let &[ref proj_base @
.., proj_elem
] = projection
{
209 ProjectionElem
::Index(index
) if in_local(index
) => return true,
211 ProjectionElem
::Deref
212 | ProjectionElem
::Field(_
, _
)
213 | ProjectionElem
::ConstantIndex { .. }
214 | ProjectionElem
::Subslice { .. }
215 | ProjectionElem
::Downcast(_
, _
)
216 | ProjectionElem
::Index(_
) => {}
219 let base_ty
= Place
::ty_from(place
.local
, proj_base
, cx
.body
, cx
.tcx
);
220 let proj_ty
= base_ty
.projection_ty(cx
.tcx
, proj_elem
).ty
;
221 if !Q
::in_any_value_of_ty(cx
, proj_ty
) {
225 projection
= proj_base
;
228 assert
!(projection
.is_empty());
229 in_local(place
.local
)
232 /// Returns `true` if this `Operand` contains qualif `Q`.
233 pub fn in_operand
<Q
, F
>(cx
: &ConstCx
<'_
, 'tcx
>, in_local
: &mut F
, operand
: &Operand
<'tcx
>) -> bool
236 F
: FnMut(Local
) -> bool
,
238 let constant
= match operand
{
239 Operand
::Copy(place
) | Operand
::Move(place
) => {
240 return in_place
::<Q
, _
>(cx
, in_local
, place
.as_ref());
243 Operand
::Constant(c
) => c
,
246 // Check the qualifs of the value of `const` items.
247 if let ty
::ConstKind
::Unevaluated(def
, _
, promoted
) = constant
.literal
.val
{
248 assert
!(promoted
.is_none());
249 // Don't peek inside trait associated constants.
250 if cx
.tcx
.trait_of_item(def
.did
).is_none() {
251 let qualifs
= if let Some((did
, param_did
)) = def
.as_const_arg() {
252 cx
.tcx
.at(constant
.span
).mir_const_qualif_const_arg((did
, param_did
))
254 cx
.tcx
.at(constant
.span
).mir_const_qualif(def
.did
)
257 if !Q
::in_qualifs(&qualifs
) {
261 // Just in case the type is more specific than
262 // the definition, e.g., impl associated const
263 // with type parameters, take it into account.
266 // Otherwise use the qualifs of the type.
267 Q
::in_any_value_of_ty(cx
, constant
.literal
.ty
)