1 use rustc::ty::query::Providers;
2 use rustc::ty::subst::{InternalSubsts, Subst};
3 use rustc::ty::{self, ParamEnvAnd, Ty, TyCtxt};
4 use rustc_data_structures::fx::FxHashSet;
5 use rustc_hir::def_id::DefId;
6 use rustc_infer::infer::canonical::{Canonical, QueryResponse};
7 use rustc_infer::infer::TyCtxtInferExt;
8 use rustc_infer::traits::query::dropck_outlives::trivial_dropck_outlives;
9 use rustc_infer::traits::query::dropck_outlives::{DropckOutlivesResult, DtorckConstraint};
10 use rustc_infer::traits::query::{CanonicalTyGoal, NoSolution};
11 use rustc_infer::traits::{Normalized, ObligationCause, TraitEngine, TraitEngineExt};
12 use rustc_span::source_map::{Span, DUMMY_SP};
14 crate fn provide(p: &mut Providers<'_>) {
15 *p = Providers { dropck_outlives, adt_dtorck_constraint, ..*p };
18 fn dropck_outlives<'tcx>(
20 canonical_goal: CanonicalTyGoal<'tcx>,
21 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, DropckOutlivesResult<'tcx>>>, NoSolution> {
22 debug!("dropck_outlives(goal={:#?})", canonical_goal);
24 tcx.infer_ctxt().enter_with_canonical(
27 |ref infcx, goal, canonical_inference_vars| {
29 let ParamEnvAnd { param_env, value: for_ty } = goal;
31 let mut result = DropckOutlivesResult { kinds: vec![], overflows: vec![] };
33 // A stack of types left to process. Each round, we pop
34 // something from the stack and invoke
35 // `dtorck_constraint_for_ty`. This may produce new types that
36 // have to be pushed on the stack. This continues until we have explored
37 // all the reachable types from the type `for_ty`.
39 // Example: Imagine that we have the following code:
54 // } // here, `a` is dropped
57 // at the point where `a` is dropped, we need to figure out
58 // which types inside of `a` contain region data that may be
59 // accessed by any destructors in `a`. We begin by pushing `A`
60 // onto the stack, as that is the type of `a`. We will then
61 // invoke `dtorck_constraint_for_ty` which will expand `A`
62 // into the types of its fields `(B, Vec<A>)`. These will get
63 // pushed onto the stack. Eventually, expanding `Vec<A>` will
64 // lead to us trying to push `A` a second time -- to prevent
65 // infinite recursion, we notice that `A` was already pushed
67 let mut ty_stack = vec![(for_ty, 0)];
69 // Set used to detect infinite recursion.
70 let mut ty_set = FxHashSet::default();
72 let mut fulfill_cx = TraitEngine::new(infcx.tcx);
74 let cause = ObligationCause::dummy();
75 let mut constraints = DtorckConstraint::empty();
76 while let Some((ty, depth)) = ty_stack.pop() {
78 "{} kinds, {} overflows, {} ty_stack",
80 result.overflows.len(),
83 dtorck_constraint_for_ty(tcx, DUMMY_SP, for_ty, depth, ty, &mut constraints)?;
85 // "outlives" represent types/regions that may be touched
87 result.kinds.extend(constraints.outlives.drain(..));
88 result.overflows.extend(constraints.overflows.drain(..));
90 // If we have even one overflow, we should stop trying to evaluate further --
91 // chances are, the subsequent overflows for this evaluation won't provide useful
92 // information and will just decrease the speed at which we can emit these errors
93 // (since we'll be printing for just that much longer for the often enormous types
95 if result.overflows.len() >= 1 {
99 // dtorck types are "types that will get dropped but which
100 // do not themselves define a destructor", more or less. We have
101 // to push them onto the stack to be expanded.
102 for ty in constraints.dtorck_types.drain(..) {
103 match infcx.at(&cause, param_env).normalize(&ty) {
104 Ok(Normalized { value: ty, obligations }) => {
105 fulfill_cx.register_predicate_obligations(infcx, obligations);
107 debug!("dropck_outlives: ty from dtorck_types = {:?}", ty);
110 // All parameters live for the duration of the
114 // A projection that we couldn't resolve - it
115 // might have a destructor.
116 ty::Projection(..) | ty::Opaque(..) => {
117 result.kinds.push(ty.into());
121 if ty_set.insert(ty) {
122 ty_stack.push((ty, depth + 1));
128 // We don't actually expect to fail to normalize.
129 // That implies a WF error somewhere else.
131 return Err(NoSolution);
137 debug!("dropck_outlives: result = {:#?}", result);
139 infcx.make_canonicalized_query_response(
140 canonical_inference_vars,
148 /// Returns a set of constraints that needs to be satisfied in
149 /// order for `ty` to be valid for destruction.
150 fn dtorck_constraint_for_ty<'tcx>(
156 constraints: &mut DtorckConstraint<'tcx>,
157 ) -> Result<(), NoSolution> {
158 debug!("dtorck_constraint_for_ty({:?}, {:?}, {:?}, {:?})", span, for_ty, depth, ty);
160 if depth >= *tcx.sess.recursion_limit.get() {
161 constraints.overflows.push(ty);
165 if trivial_dropck_outlives(tcx, ty) {
182 | ty::GeneratorWitness(..) => {
183 // these types never have a destructor
186 ty::Array(ety, _) | ty::Slice(ety) => {
187 // single-element containers, behave like their element
188 dtorck_constraint_for_ty(tcx, span, for_ty, depth + 1, ety, constraints)?;
192 for ty in tys.iter() {
193 dtorck_constraint_for_ty(
204 ty::Closure(def_id, substs) => {
205 for ty in substs.as_closure().upvar_tys(def_id, tcx) {
206 dtorck_constraint_for_ty(tcx, span, for_ty, depth + 1, ty, constraints)?;
210 ty::Generator(def_id, substs, _movability) => {
211 // rust-lang/rust#49918: types can be constructed, stored
212 // in the interior, and sit idle when generator yields
213 // (and is subsequently dropped).
215 // It would be nice to descend into interior of a
216 // generator to determine what effects dropping it might
217 // have (by looking at any drop effects associated with
220 // However, the interior's representation uses things like
221 // GeneratorWitness that explicitly assume they are not
222 // traversed in such a manner. So instead, we will
223 // simplify things for now by treating all generators as
224 // if they were like trait objects, where its upvars must
225 // all be alive for the generator's (potential)
228 // In particular, skipping over `_interior` is safe
229 // because any side-effects from dropping `_interior` can
230 // only take place through references with lifetimes
231 // derived from lifetimes attached to the upvars and resume
232 // argument, and we *do* incorporate those here.
234 constraints.outlives.extend(
237 .upvar_tys(def_id, tcx)
238 .map(|t| -> ty::subst::GenericArg<'tcx> { t.into() }),
240 constraints.outlives.push(substs.as_generator().resume_ty(def_id, tcx).into());
243 ty::Adt(def, substs) => {
244 let DtorckConstraint { dtorck_types, outlives, overflows } =
245 tcx.at(span).adt_dtorck_constraint(def.did)?;
246 // FIXME: we can try to recursively `dtorck_constraint_on_ty`
247 // there, but that needs some way to handle cycles.
248 constraints.dtorck_types.extend(dtorck_types.subst(tcx, substs));
249 constraints.outlives.extend(outlives.subst(tcx, substs));
250 constraints.overflows.extend(overflows.subst(tcx, substs));
253 // Objects must be alive in order for their destructor
256 constraints.outlives.push(ty.into());
259 // Types that can't be resolved. Pass them forward.
260 ty::Projection(..) | ty::Opaque(..) | ty::Param(..) => {
261 constraints.dtorck_types.push(ty);
264 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
266 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error => {
267 // By the time this code runs, all type variables ought to
268 // be fully resolved.
269 return Err(NoSolution);
276 /// Calculates the dtorck constraint for a type.
277 crate fn adt_dtorck_constraint(
280 ) -> Result<DtorckConstraint<'_>, NoSolution> {
281 let def = tcx.adt_def(def_id);
282 let span = tcx.def_span(def_id);
283 debug!("dtorck_constraint: {:?}", def);
285 if def.is_phantom_data() {
286 // The first generic parameter here is guaranteed to be a type because it's
288 let substs = InternalSubsts::identity_for_item(tcx, def_id);
289 assert_eq!(substs.len(), 1);
290 let result = DtorckConstraint {
292 dtorck_types: vec![substs.type_at(0)],
295 debug!("dtorck_constraint: {:?} => {:?}", def, result);
299 let mut result = DtorckConstraint::empty();
300 for field in def.all_fields() {
301 let fty = tcx.type_of(field.did);
302 dtorck_constraint_for_ty(tcx, span, fty, 0, fty, &mut result)?;
304 result.outlives.extend(tcx.destructor_constraints(def));
305 dedup_dtorck_constraint(&mut result);
307 debug!("dtorck_constraint: {:?} => {:?}", def, result);
312 fn dedup_dtorck_constraint(c: &mut DtorckConstraint<'_>) {
313 let mut outlives = FxHashSet::default();
314 let mut dtorck_types = FxHashSet::default();
316 c.outlives.retain(|&val| outlives.replace(val).is_none());
317 c.dtorck_types.retain(|&val| dtorck_types.replace(val).is_none());