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