]> git.lizzy.rs Git - rust.git/blob - src/librustc_traits/dropck_outlives.rs
7db1a7413c7be27351560ea7a5555cdeda478388
[rust.git] / src / librustc_traits / dropck_outlives.rs
1 use rustc::hir::def_id::DefId;
2 use rustc::infer::canonical::{Canonical, QueryResponse};
3 use rustc::traits::query::dropck_outlives::{DropckOutlivesResult, DtorckConstraint};
4 use rustc::traits::query::{CanonicalTyGoal, NoSolution};
5 use rustc::traits::{TraitEngine, Normalized, ObligationCause, TraitEngineExt};
6 use rustc::ty::query::Providers;
7 use rustc::ty::subst::{Subst, InternalSubsts};
8 use rustc::ty::{self, ParamEnvAnd, Ty, TyCtxt};
9 use rustc::util::nodemap::FxHashSet;
10 use syntax::source_map::{Span, DUMMY_SP};
11
12 crate fn provide(p: &mut Providers<'_>) {
13     *p = Providers {
14         dropck_outlives,
15         adt_dtorck_constraint,
16         ..*p
17     };
18 }
19
20 fn dropck_outlives<'tcx>(
21     tcx: TyCtxt<'tcx>,
22     canonical_goal: CanonicalTyGoal<'tcx>,
23 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, DropckOutlivesResult<'tcx>>>, NoSolution> {
24     debug!("dropck_outlives(goal={:#?})", canonical_goal);
25
26     tcx.infer_ctxt().enter_with_canonical(
27         DUMMY_SP,
28         &canonical_goal,
29         |ref infcx, goal, canonical_inference_vars| {
30             let tcx = infcx.tcx;
31             let ParamEnvAnd {
32                 param_env,
33                 value: for_ty,
34             } = goal;
35
36             let mut result = DropckOutlivesResult {
37                 kinds: vec![],
38                 overflows: vec![],
39             };
40
41             // A stack of types left to process. Each round, we pop
42             // something from the stack and invoke
43             // `dtorck_constraint_for_ty`. This may produce new types that
44             // have to be pushed on the stack. This continues until we have explored
45             // all the reachable types from the type `for_ty`.
46             //
47             // Example: Imagine that we have the following code:
48             //
49             // ```rust
50             // struct A {
51             //     value: B,
52             //     children: Vec<A>,
53             // }
54             //
55             // struct B {
56             //     value: u32
57             // }
58             //
59             // fn f() {
60             //   let a: A = ...;
61             //   ..
62             // } // here, `a` is dropped
63             // ```
64             //
65             // at the point where `a` is dropped, we need to figure out
66             // which types inside of `a` contain region data that may be
67             // accessed by any destructors in `a`. We begin by pushing `A`
68             // onto the stack, as that is the type of `a`. We will then
69             // invoke `dtorck_constraint_for_ty` which will expand `A`
70             // into the types of its fields `(B, Vec<A>)`. These will get
71             // pushed onto the stack. Eventually, expanding `Vec<A>` will
72             // lead to us trying to push `A` a second time -- to prevent
73             // infinite recursion, we notice that `A` was already pushed
74             // once and stop.
75             let mut ty_stack = vec![(for_ty, 0)];
76
77             // Set used to detect infinite recursion.
78             let mut ty_set = FxHashSet::default();
79
80             let mut fulfill_cx = TraitEngine::new(infcx.tcx);
81
82             let cause = ObligationCause::dummy();
83             while let Some((ty, depth)) = ty_stack.pop() {
84                 let DtorckConstraint {
85                     dtorck_types,
86                     outlives,
87                     overflows,
88                 } = dtorck_constraint_for_ty(tcx, DUMMY_SP, for_ty, depth, ty)?;
89
90                 // "outlives" represent types/regions that may be touched
91                 // by a destructor.
92                 result.kinds.extend(outlives);
93                 result.overflows.extend(overflows);
94
95                 // dtorck types are "types that will get dropped but which
96                 // do not themselves define a destructor", more or less. We have
97                 // to push them onto the stack to be expanded.
98                 for ty in dtorck_types {
99                     match infcx.at(&cause, param_env).normalize(&ty) {
100                         Ok(Normalized {
101                             value: ty,
102                             obligations,
103                         }) => {
104                             fulfill_cx.register_predicate_obligations(infcx, obligations);
105
106                             debug!("dropck_outlives: ty from dtorck_types = {:?}", ty);
107
108                             match ty.kind {
109                                 // All parameters live for the duration of the
110                                 // function.
111                                 ty::Param(..) => {}
112
113                                 // A projection that we couldn't resolve - it
114                                 // might have a destructor.
115                                 ty::Projection(..) | ty::Opaque(..) => {
116                                     result.kinds.push(ty.into());
117                                 }
118
119                                 _ => {
120                                     if ty_set.insert(ty) {
121                                         ty_stack.push((ty, depth + 1));
122                                     }
123                                 }
124                             }
125                         }
126
127                         // We don't actually expect to fail to normalize.
128                         // That implies a WF error somewhere else.
129                         Err(NoSolution) => {
130                             return Err(NoSolution);
131                         }
132                     }
133                 }
134             }
135
136             debug!("dropck_outlives: result = {:#?}", result);
137
138             infcx.make_canonicalized_query_response(
139                 canonical_inference_vars,
140                 result,
141                 &mut *fulfill_cx
142             )
143         },
144     )
145 }
146
147 /// Returns a set of constraints that needs to be satisfied in
148 /// order for `ty` to be valid for destruction.
149 fn dtorck_constraint_for_ty<'tcx>(
150     tcx: TyCtxt<'tcx>,
151     span: Span,
152     for_ty: Ty<'tcx>,
153     depth: usize,
154     ty: Ty<'tcx>,
155 ) -> Result<DtorckConstraint<'tcx>, NoSolution> {
156     debug!(
157         "dtorck_constraint_for_ty({:?}, {:?}, {:?}, {:?})",
158         span, for_ty, depth, ty
159     );
160
161     if depth >= *tcx.sess.recursion_limit.get() {
162         return Ok(DtorckConstraint {
163             outlives: vec![],
164             dtorck_types: vec![],
165             overflows: vec![ty],
166         });
167     }
168
169     let result = match ty.kind {
170         ty::Bool
171         | ty::Char
172         | ty::Int(_)
173         | ty::Uint(_)
174         | ty::Float(_)
175         | ty::Str
176         | ty::Never
177         | ty::Foreign(..)
178         | ty::RawPtr(..)
179         | ty::Ref(..)
180         | ty::FnDef(..)
181         | ty::FnPtr(_)
182         | ty::GeneratorWitness(..) => {
183             // these types never have a destructor
184             Ok(DtorckConstraint::empty())
185         }
186
187         ty::Array(ety, _) | ty::Slice(ety) => {
188             // single-element containers, behave like their element
189             dtorck_constraint_for_ty(tcx, span, for_ty, depth + 1, ety)
190         }
191
192         ty::Tuple(tys) => tys.iter()
193             .map(|ty| dtorck_constraint_for_ty(tcx, span, for_ty, depth + 1, ty.expect_ty()))
194             .collect(),
195
196         ty::Closure(def_id, substs) => substs.as_closure()
197             .upvar_tys(def_id, tcx)
198             .map(|ty| dtorck_constraint_for_ty(tcx, span, for_ty, depth + 1, ty))
199             .collect(),
200
201         ty::Generator(def_id, substs, _movability) => {
202             // rust-lang/rust#49918: types can be constructed, stored
203             // in the interior, and sit idle when generator yields
204             // (and is subsequently dropped).
205             //
206             // It would be nice to descend into interior of a
207             // generator to determine what effects dropping it might
208             // have (by looking at any drop effects associated with
209             // its interior).
210             //
211             // However, the interior's representation uses things like
212             // GeneratorWitness that explicitly assume they are not
213             // traversed in such a manner. So instead, we will
214             // simplify things for now by treating all generators as
215             // if they were like trait objects, where its upvars must
216             // all be alive for the generator's (potential)
217             // destructor.
218             //
219             // In particular, skipping over `_interior` is safe
220             // because any side-effects from dropping `_interior` can
221             // only take place through references with lifetimes
222             // derived from lifetimes attached to the upvars, and we
223             // *do* incorporate the upvars here.
224
225             let constraint = DtorckConstraint {
226                 outlives: substs.upvar_tys(def_id, tcx).map(|t| t.into()).collect(),
227                 dtorck_types: vec![],
228                 overflows: vec![],
229             };
230             debug!(
231                 "dtorck_constraint: generator {:?} => {:?}",
232                 def_id, constraint
233             );
234
235             Ok(constraint)
236         }
237
238         ty::Adt(def, substs) => {
239             let DtorckConstraint {
240                 dtorck_types,
241                 outlives,
242                 overflows,
243             } = tcx.at(span).adt_dtorck_constraint(def.did)?;
244             Ok(DtorckConstraint {
245                 // FIXME: we can try to recursively `dtorck_constraint_on_ty`
246                 // there, but that needs some way to handle cycles.
247                 dtorck_types: dtorck_types.subst(tcx, substs),
248                 outlives: outlives.subst(tcx, substs),
249                 overflows: overflows.subst(tcx, substs),
250             })
251         }
252
253         // Objects must be alive in order for their destructor
254         // to be called.
255         ty::Dynamic(..) => Ok(DtorckConstraint {
256             outlives: vec![ty.into()],
257             dtorck_types: vec![],
258             overflows: vec![],
259         }),
260
261         // Types that can't be resolved. Pass them forward.
262         ty::Projection(..) | ty::Opaque(..) | ty::Param(..) => Ok(DtorckConstraint {
263             outlives: vec![],
264             dtorck_types: vec![ty],
265             overflows: vec![],
266         }),
267
268         ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
269
270         ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error => {
271             // By the time this code runs, all type variables ought to
272             // be fully resolved.
273             Err(NoSolution)
274         }
275     };
276
277     debug!("dtorck_constraint_for_ty({:?}) = {:?}", ty, result);
278     result
279 }
280
281 /// Calculates the dtorck constraint for a type.
282 crate fn adt_dtorck_constraint(
283     tcx: TyCtxt<'_>,
284     def_id: DefId,
285 ) -> Result<DtorckConstraint<'_>, NoSolution> {
286     let def = tcx.adt_def(def_id);
287     let span = tcx.def_span(def_id);
288     debug!("dtorck_constraint: {:?}", def);
289
290     if def.is_phantom_data() {
291         // The first generic parameter here is guaranteed to be a type because it's
292         // `PhantomData`.
293         let substs = InternalSubsts::identity_for_item(tcx, def_id);
294         assert_eq!(substs.len(), 1);
295         let result = DtorckConstraint {
296             outlives: vec![],
297             dtorck_types: vec![substs.type_at(0)],
298             overflows: vec![],
299         };
300         debug!("dtorck_constraint: {:?} => {:?}", def, result);
301         return Ok(result);
302     }
303
304     let mut result = def.all_fields()
305         .map(|field| tcx.type_of(field.did))
306         .map(|fty| dtorck_constraint_for_ty(tcx, span, fty, 0, fty))
307         .collect::<Result<DtorckConstraint<'_>, NoSolution>>()?;
308     result.outlives.extend(tcx.destructor_constraints(def));
309     dedup_dtorck_constraint(&mut result);
310
311     debug!("dtorck_constraint: {:?} => {:?}", def, result);
312
313     Ok(result)
314 }
315
316 fn dedup_dtorck_constraint(c: &mut DtorckConstraint<'_>) {
317     let mut outlives = FxHashSet::default();
318     let mut dtorck_types = FxHashSet::default();
319
320     c.outlives.retain(|&val| outlives.replace(val).is_none());
321     c.dtorck_types
322         .retain(|&val| dtorck_types.replace(val).is_none());
323 }