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};
12 crate fn provide(p: &mut Providers<'_>) {
15 adt_dtorck_constraint,
20 fn dropck_outlives<'tcx>(
21 tcx: TyCtxt<'_, 'tcx, 'tcx>,
22 canonical_goal: CanonicalTyGoal<'tcx>,
23 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, DropckOutlivesResult<'tcx>>>, NoSolution> {
24 debug!("dropck_outlives(goal={:#?})", canonical_goal);
26 tcx.infer_ctxt().enter_with_canonical(
29 |ref infcx, goal, canonical_inference_vars| {
36 let mut result = DropckOutlivesResult {
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`.
47 // Example: Imagine that we have the following code:
62 // } // here, `a` is dropped
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
75 let mut ty_stack = vec![(for_ty, 0)];
77 // Set used to detect infinite recursion.
78 let mut ty_set = FxHashSet::default();
80 let mut fulfill_cx = TraitEngine::new(infcx.tcx);
82 let cause = ObligationCause::dummy();
83 while let Some((ty, depth)) = ty_stack.pop() {
84 let DtorckConstraint {
88 } = dtorck_constraint_for_ty(tcx, DUMMY_SP, for_ty, depth, ty)?;
90 // "outlives" represent types/regions that may be touched
92 result.kinds.extend(outlives);
93 result.overflows.extend(overflows);
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) {
104 fulfill_cx.register_predicate_obligations(infcx, obligations);
106 debug!("dropck_outlives: ty from dtorck_types = {:?}", ty);
109 // All parameters live for the duration of the
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());
120 if ty_set.insert(ty) {
121 ty_stack.push((ty, depth + 1));
127 // We don't actually expect to fail to normalize.
128 // That implies a WF error somewhere else.
130 return Err(NoSolution);
136 debug!("dropck_outlives: result = {:#?}", result);
138 infcx.make_canonicalized_query_response(
139 canonical_inference_vars,
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<'a, 'gcx, 'tcx>(
150 tcx: TyCtxt<'a, 'gcx, 'tcx>,
155 ) -> Result<DtorckConstraint<'tcx>, NoSolution> {
157 "dtorck_constraint_for_ty({:?}, {:?}, {:?}, {:?})",
158 span, for_ty, depth, ty
161 if depth >= *tcx.sess.recursion_limit.get() {
162 return Ok(DtorckConstraint {
164 dtorck_types: vec![],
169 let result = match ty.sty {
182 | ty::GeneratorWitness(..) => {
183 // these types never have a destructor
184 Ok(DtorckConstraint::empty())
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)
192 ty::Tuple(tys) => tys.iter()
193 .map(|ty| dtorck_constraint_for_ty(tcx, span, for_ty, depth + 1, ty.expect_ty()))
196 ty::Closure(def_id, substs) => substs
197 .upvar_tys(def_id, tcx)
198 .map(|ty| dtorck_constraint_for_ty(tcx, span, for_ty, depth + 1, ty))
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).
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
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)
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.
225 let constraint = DtorckConstraint {
226 outlives: substs.upvar_tys(def_id, tcx).map(|t| t.into()).collect(),
227 dtorck_types: vec![],
231 "dtorck_constraint: generator {:?} => {:?}",
238 ty::Adt(def, substs) => {
239 let DtorckConstraint {
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),
253 // Objects must be alive in order for their destructor
255 ty::Dynamic(..) => Ok(DtorckConstraint {
256 outlives: vec![ty.into()],
257 dtorck_types: vec![],
261 // Types that can't be resolved. Pass them forward.
262 ty::Projection(..) | ty::Opaque(..) | ty::Param(..) => Ok(DtorckConstraint {
264 dtorck_types: vec![ty],
268 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
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.
277 debug!("dtorck_constraint_for_ty({:?}) = {:?}", ty, result);
281 /// Calculates the dtorck constraint for a type.
282 crate fn adt_dtorck_constraint<'a, 'tcx>(
283 tcx: TyCtxt<'a, 'tcx, 'tcx>,
285 ) -> Result<DtorckConstraint<'tcx>, NoSolution> {
286 let def = tcx.adt_def(def_id);
287 let span = tcx.def_span(def_id);
288 debug!("dtorck_constraint: {:?}", def);
290 if def.is_phantom_data() {
291 // The first generic parameter here is guaranteed to be a type because it's
293 let substs = InternalSubsts::identity_for_item(tcx, def_id);
294 assert_eq!(substs.len(), 1);
295 let result = DtorckConstraint {
297 dtorck_types: vec![substs.type_at(0)],
300 debug!("dtorck_constraint: {:?} => {:?}", def, result);
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);
311 debug!("dtorck_constraint: {:?} => {:?}", def, result);
316 fn dedup_dtorck_constraint<'tcx>(c: &mut DtorckConstraint<'tcx>) {
317 let mut outlives = FxHashSet::default();
318 let mut dtorck_types = FxHashSet::default();
320 c.outlives.retain(|&val| outlives.replace(val).is_none());
322 .retain(|&val| dtorck_types.replace(val).is_none());