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