]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/check_consts/qualifs.rs
Rollup merge of #70038 - DutchGhost:const-forget-tests, r=RalfJung
[rust.git] / src / librustc_mir / transform / check_consts / qualifs.rs
1 //! Structural const qualification.
2 //!
3 //! See the `Qualif` trait for more info.
4
5 use rustc::mir::*;
6 use rustc::ty::{self, AdtDef, Ty};
7 use rustc_span::DUMMY_SP;
8
9 use super::Item as ConstCx;
10
11 pub fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> ConstQualifs {
12     ConstQualifs {
13         has_mut_interior: HasMutInterior::in_any_value_of_ty(cx, ty),
14         needs_drop: NeedsDrop::in_any_value_of_ty(cx, ty),
15     }
16 }
17
18 /// A "qualif"(-ication) is a way to look for something "bad" in the MIR that would disqualify some
19 /// code for promotion or prevent it from evaluating at compile time.
20 ///
21 /// Normally, we would determine what qualifications apply to each type and error when an illegal
22 /// operation is performed on such a type. However, this was found to be too imprecise, especially
23 /// in the presence of `enum`s. If only a single variant of an enum has a certain qualification, we
24 /// needn't reject code unless it actually constructs and operates on the qualifed variant.
25 ///
26 /// To accomplish this, const-checking and promotion use a value-based analysis (as opposed to a
27 /// type-based one). Qualifications propagate structurally across variables: If a local (or a
28 /// projection of a local) is assigned a qualifed value, that local itself becomes qualifed.
29 pub trait Qualif {
30     /// The name of the file used to debug the dataflow analysis that computes this qualif.
31     const ANALYSIS_NAME: &'static str;
32
33     /// Whether this `Qualif` is cleared when a local is moved from.
34     const IS_CLEARED_ON_MOVE: bool = false;
35
36     /// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`.
37     fn in_qualifs(qualifs: &ConstQualifs) -> bool;
38
39     /// Returns `true` if *any* value of the given type could possibly have this `Qualif`.
40     ///
41     /// This function determines `Qualif`s when we cannot do a value-based analysis. Since qualif
42     /// propagation is context-insenstive, this includes function arguments and values returned
43     /// from a call to another function.
44     ///
45     /// It also determines the `Qualif`s for primitive types.
46     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool;
47
48     /// Returns `true` if this `Qualif` is inherent to the given struct or enum.
49     ///
50     /// By default, `Qualif`s propagate into ADTs in a structural way: An ADT only becomes
51     /// qualified if part of it is assigned a value with that `Qualif`. However, some ADTs *always*
52     /// have a certain `Qualif`, regardless of whether their fields have it. For example, a type
53     /// with a custom `Drop` impl is inherently `NeedsDrop`.
54     ///
55     /// Returning `true` for `in_adt_inherently` but `false` for `in_any_value_of_ty` is unsound.
56     fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &AdtDef) -> bool;
57 }
58
59 /// Constant containing interior mutability (`UnsafeCell<T>`).
60 /// This must be ruled out to make sure that evaluating the constant at compile-time
61 /// and at *any point* during the run-time would produce the same result. In particular,
62 /// promotion of temporaries must not change program behavior; if the promoted could be
63 /// written to, that would be a problem.
64 pub struct HasMutInterior;
65
66 impl Qualif for HasMutInterior {
67     const ANALYSIS_NAME: &'static str = "flow_has_mut_interior";
68
69     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
70         qualifs.has_mut_interior
71     }
72
73     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
74         !ty.is_freeze(cx.tcx, cx.param_env, DUMMY_SP)
75     }
76
77     fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &AdtDef) -> bool {
78         // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently.
79         // It arises structurally for all other types.
80         Some(adt.did) == cx.tcx.lang_items().unsafe_cell_type()
81     }
82 }
83
84 /// Constant containing an ADT that implements `Drop`.
85 /// This must be ruled out (a) because we cannot run `Drop` during compile-time
86 /// as that might not be a `const fn`, and (b) because implicit promotion would
87 /// remove side-effects that occur as part of dropping that value.
88 pub struct NeedsDrop;
89
90 impl Qualif for NeedsDrop {
91     const ANALYSIS_NAME: &'static str = "flow_needs_drop";
92     const IS_CLEARED_ON_MOVE: bool = true;
93
94     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
95         qualifs.needs_drop
96     }
97
98     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
99         ty.needs_drop(cx.tcx, cx.param_env)
100     }
101
102     fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &AdtDef) -> bool {
103         adt.has_dtor(cx.tcx)
104     }
105 }
106
107 // FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
108
109 /// Returns `true` if this `Rvalue` contains qualif `Q`.
110 pub fn in_rvalue<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, rvalue: &Rvalue<'tcx>) -> bool
111 where
112     Q: Qualif,
113     F: FnMut(Local) -> bool,
114 {
115     match rvalue {
116         Rvalue::NullaryOp(..) => Q::in_any_value_of_ty(cx, rvalue.ty(*cx.body, cx.tcx)),
117
118         Rvalue::Discriminant(place) | Rvalue::Len(place) => {
119             in_place::<Q, _>(cx, in_local, place.as_ref())
120         }
121
122         Rvalue::Use(operand)
123         | Rvalue::Repeat(operand, _)
124         | Rvalue::UnaryOp(_, operand)
125         | Rvalue::Cast(_, operand, _) => in_operand::<Q, _>(cx, in_local, operand),
126
127         Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
128             in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
129         }
130
131         Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
132             // Special-case reborrows to be more like a copy of the reference.
133             if let &[ref proj_base @ .., ProjectionElem::Deref] = place.projection.as_ref() {
134                 let base_ty = Place::ty_from(place.local, proj_base, *cx.body, cx.tcx).ty;
135                 if let ty::Ref(..) = base_ty.kind {
136                     return in_place::<Q, _>(
137                         cx,
138                         in_local,
139                         PlaceRef { local: place.local, projection: proj_base },
140                     );
141                 }
142             }
143
144             in_place::<Q, _>(cx, in_local, place.as_ref())
145         }
146
147         Rvalue::Aggregate(kind, operands) => {
148             // Return early if we know that the struct or enum being constructed is always
149             // qualified.
150             if let AggregateKind::Adt(def, ..) = **kind {
151                 if Q::in_adt_inherently(cx, def) {
152                     return true;
153                 }
154             }
155
156             // Otherwise, proceed structurally...
157             operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o))
158         }
159     }
160 }
161
162 /// Returns `true` if this `Place` contains qualif `Q`.
163 pub fn in_place<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool
164 where
165     Q: Qualif,
166     F: FnMut(Local) -> bool,
167 {
168     let mut projection = place.projection;
169     while let [ref proj_base @ .., proj_elem] = projection {
170         match *proj_elem {
171             ProjectionElem::Index(index) if in_local(index) => return true,
172
173             ProjectionElem::Deref
174             | ProjectionElem::Field(_, _)
175             | ProjectionElem::ConstantIndex { .. }
176             | ProjectionElem::Subslice { .. }
177             | ProjectionElem::Downcast(_, _)
178             | ProjectionElem::Index(_) => {}
179         }
180
181         let base_ty = Place::ty_from(place.local, proj_base, *cx.body, cx.tcx);
182         let proj_ty = base_ty.projection_ty(cx.tcx, proj_elem).ty;
183         if !Q::in_any_value_of_ty(cx, proj_ty) {
184             return false;
185         }
186
187         projection = proj_base;
188     }
189
190     assert!(projection.is_empty());
191     in_local(place.local)
192 }
193
194 /// Returns `true` if this `Operand` contains qualif `Q`.
195 pub fn in_operand<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, operand: &Operand<'tcx>) -> bool
196 where
197     Q: Qualif,
198     F: FnMut(Local) -> bool,
199 {
200     let constant = match operand {
201         Operand::Copy(place) | Operand::Move(place) => {
202             return in_place::<Q, _>(cx, in_local, place.as_ref());
203         }
204
205         Operand::Constant(c) => c,
206     };
207
208     // Check the qualifs of the value of `const` items.
209     if let ty::ConstKind::Unevaluated(def_id, _, promoted) = constant.literal.val {
210         assert!(promoted.is_none());
211         // Don't peek inside trait associated constants.
212         if cx.tcx.trait_of_item(def_id).is_none() {
213             let qualifs = cx.tcx.at(constant.span).mir_const_qualif(def_id);
214             if !Q::in_qualifs(&qualifs) {
215                 return false;
216             }
217
218             // Just in case the type is more specific than
219             // the definition, e.g., impl associated const
220             // with type parameters, take it into account.
221         }
222     }
223     // Otherwise use the qualifs of the type.
224     Q::in_any_value_of_ty(cx, constant.literal.ty)
225 }