]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_infer/src/infer/outlives/obligations.rs
New upstream version 1.53.0+dfsg1
[rustc.git] / compiler / rustc_infer / src / infer / outlives / obligations.rs
CommitLineData
abe05a73 1//! Code that handles "type-outlives" constraints like `T: 'a`. This
a1dfa0c6 2//! is based on the `push_outlives_components` function defined on the tcx,
abe05a73
XL
3//! but it adds a bit of heuristics on top, in particular to deal with
4//! associated types and projections.
5//!
6//! When we process a given `T: 'a` obligation, we may produce two
7//! kinds of constraints for the region inferencer:
8//!
9//! - Relationships between inference variables and other regions.
10//! For example, if we have `&'?0 u32: 'a`, then we would produce
11//! a constraint that `'a <= '?0`.
12//! - "Verifys" that must be checked after inferencing is done.
13//! For example, if we know that, for some type parameter `T`,
14//! `T: 'a + 'b`, and we have a requirement that `T: '?1`,
15//! then we add a "verify" that checks that `'?1 <= 'a || '?1 <= 'b`.
16//! - Note the difference with the previous case: here, the region
17//! variable must be less than something else, so this doesn't
18//! affect how inference works (it finds the smallest region that
19//! will do); it's just a post-condition that we have to check.
20//!
21//! **The key point is that once this function is done, we have
22//! reduced all of our "type-region outlives" obligations into relationships
23//! between individual regions.**
24//!
25//! One key input to this function is the set of "region-bound pairs".
26//! These are basically the relationships between type parameters and
27//! regions that are in scope at the point where the outlives
28//! obligation was incurred. **When type-checking a function,
29//! particularly in the face of closures, this is not known until
30//! regionck runs!** This is because some of those bounds come
31//! from things we have yet to infer.
32//!
33//! Consider:
34//!
35//! ```
36//! fn bar<T>(a: T, b: impl for<'a> Fn(&'a T));
37//! fn foo<T>(x: T) {
38//! bar(x, |y| { ... })
39//! // ^ closure arg
40//! }
41//! ```
42//!
43//! Here, the type of `y` may involve inference variables and the
44//! like, and it may also contain implied bounds that are needed to
45//! type-check the closure body (e.g., here it informs us that `T`
46//! outlives the late-bound region `'a`).
47//!
48//! Note that by delaying the gathering of implied bounds until all
49//! inference information is known, we may find relationships between
50//! bound regions and other regions in the environment. For example,
51//! when we first check a closure like the one expected as argument
52//! to `foo`:
53//!
54//! ```
55//! fn foo<U, F: for<'a> FnMut(&'a U)>(_f: F) {}
56//! ```
57//!
9fa01778 58//! the type of the closure's first argument would be `&'a ?U`. We
abe05a73
XL
59//! might later infer `?U` to something like `&'b u32`, which would
60//! imply that `'b: 'a`.
61
9fa01778
XL
62use crate::infer::outlives::env::RegionBoundPairs;
63use crate::infer::outlives::verify::VerifyBoundCx;
f9f354fc
XL
64use crate::infer::{
65 self, GenericKind, InferCtxt, RegionObligation, SubregionOrigin, UndoLog, VerifyBound,
66};
9fa01778 67use crate::traits::ObligationCause;
ba9703b0
XL
68use rustc_middle::ty::outlives::Component;
69use rustc_middle::ty::subst::GenericArgKind;
70use rustc_middle::ty::{self, Region, Ty, TyCtxt, TypeFoldable};
74b04a01 71
dfeec247 72use rustc_data_structures::fx::FxHashMap;
f9f354fc 73use rustc_data_structures::undo_log::UndoLogs;
dfeec247 74use rustc_hir as hir;
74b04a01 75use smallvec::smallvec;
abe05a73 76
dc9dc135 77impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
abe05a73
XL
78 /// Registers that the given region obligation must be resolved
79 /// from within the scope of `body_id`. These regions are enqueued
80 /// and later processed by regionck, when full type information is
81 /// available (see `region_obligations` field for more
82 /// information).
83 pub fn register_region_obligation(
84 &self,
9fa01778 85 body_id: hir::HirId,
abe05a73
XL
86 obligation: RegionObligation<'tcx>,
87 ) {
dfeec247 88 debug!("register_region_obligation(body_id={:?}, obligation={:?})", body_id, obligation);
ff7c6d11 89
f9f354fc
XL
90 let mut inner = self.inner.borrow_mut();
91 inner.undo_log.push(UndoLog::PushRegionObligation);
92 inner.region_obligations.push((body_id, obligation));
abe05a73
XL
93 }
94
0bf4aa26
XL
95 pub fn register_region_obligation_with_cause(
96 &self,
97 sup_type: Ty<'tcx>,
98 sub_region: Region<'tcx>,
99 cause: &ObligationCause<'tcx>,
100 ) {
101 let origin = SubregionOrigin::from_obligation_cause(cause, || {
102 infer::RelateParamBound(cause.span, sup_type)
103 });
104
105 self.register_region_obligation(
106 cause.body_id,
dfeec247 107 RegionObligation { sup_type, sub_region, origin },
0bf4aa26
XL
108 );
109 }
110
0531ce1d 111 /// Trait queries just want to pass back type obligations "as is"
9fa01778 112 pub fn take_registered_region_obligations(&self) -> Vec<(hir::HirId, RegionObligation<'tcx>)> {
29967ef6 113 std::mem::take(&mut self.inner.borrow_mut().region_obligations)
0531ce1d
XL
114 }
115
abe05a73
XL
116 /// Process the region obligations that must be proven (during
117 /// `regionck`) for the given `body_id`, given information about
118 /// the region bounds in scope and so forth. This function must be
119 /// invoked for all relevant body-ids before region inference is
120 /// done (or else an assert will fire).
121 ///
122 /// See the `region_obligations` field of `InferCtxt` for some
0531ce1d 123 /// comments about how this function fits into the overall expected
a1dfa0c6 124 /// flow of the inferencer. The key point is that it is
abe05a73
XL
125 /// invoked after all type-inference variables have been bound --
126 /// towards the end of regionck. This also ensures that the
127 /// region-bound-pairs are available (see comments above regarding
128 /// closures).
129 ///
130 /// # Parameters
131 ///
132 /// - `region_bound_pairs`: the set of region bounds implied by
133 /// the parameters and where-clauses. In particular, each pair
134 /// `('a, K)` in this list tells us that the bounds in scope
135 /// indicate that `K: 'a`, where `K` is either a generic
136 /// parameter like `T` or a projection like `T::Item`.
137 /// - `implicit_region_bound`: if some, this is a region bound
138 /// that is considered to hold for all type parameters (the
139 /// function body).
140 /// - `param_env` is the parameter environment for the enclosing function.
141 /// - `body_id` is the body-id whose region obligations are being
142 /// processed.
143 ///
144 /// # Returns
145 ///
146 /// This function may have to perform normalizations, and hence it
147 /// returns an `InferOk` with subobligations that must be
148 /// processed.
149 pub fn process_registered_region_obligations(
150 &self,
9fa01778 151 region_bound_pairs_map: &FxHashMap<hir::HirId, RegionBoundPairs<'tcx>>,
abe05a73
XL
152 implicit_region_bound: Option<ty::Region<'tcx>>,
153 param_env: ty::ParamEnv<'tcx>,
abe05a73
XL
154 ) {
155 assert!(
156 !self.in_snapshot.get(),
157 "cannot process registered region obligations in a snapshot"
158 );
159
ff7c6d11
XL
160 debug!("process_registered_region_obligations()");
161
0bf4aa26 162 let my_region_obligations = self.take_registered_region_obligations();
abe05a73 163
dfeec247 164 for (body_id, RegionObligation { sup_type, sub_region, origin }) in my_region_obligations {
ff7c6d11 165 debug!(
0bf4aa26
XL
166 "process_registered_region_obligations: sup_type={:?} sub_region={:?} origin={:?}",
167 sup_type, sub_region, origin
ff7c6d11
XL
168 );
169
fc512014 170 let sup_type = self.resolve_vars_if_possible(sup_type);
0bf4aa26
XL
171
172 if let Some(region_bound_pairs) = region_bound_pairs_map.get(&body_id) {
173 let outlives = &mut TypeOutlives::new(
174 self,
175 self.tcx,
176 &region_bound_pairs,
177 implicit_region_bound,
178 param_env,
179 );
180 outlives.type_must_outlive(origin, sup_type, sub_region);
181 } else {
182 self.tcx.sess.delay_span_bug(
183 origin.span(),
184 &format!("no region-bound-pairs for {:?}", body_id),
185 )
186 }
abe05a73
XL
187 }
188 }
abe05a73
XL
189}
190
8faf50e0 191/// The `TypeOutlives` struct has the job of "lowering" a `T: 'a`
60c5eb7d 192/// obligation into a series of `'a: 'b` constraints and "verify"s, as
8faf50e0
XL
193/// described on the module comment. The final constraints are emitted
194/// via a "delegate" of type `D` -- this is usually the `infcx`, which
195/// accrues them into the `region_obligations` code, but for NLL we
196/// use something else.
dc9dc135 197pub struct TypeOutlives<'cx, 'tcx, D>
8faf50e0
XL
198where
199 D: TypeOutlivesDelegate<'tcx>,
200{
abe05a73
XL
201 // See the comments on `process_registered_region_obligations` for the meaning
202 // of these fields.
8faf50e0 203 delegate: D,
dc9dc135
XL
204 tcx: TyCtxt<'tcx>,
205 verify_bound: VerifyBoundCx<'cx, 'tcx>,
abe05a73
XL
206}
207
8faf50e0
XL
208pub trait TypeOutlivesDelegate<'tcx> {
209 fn push_sub_region_constraint(
210 &mut self,
211 origin: SubregionOrigin<'tcx>,
212 a: ty::Region<'tcx>,
213 b: ty::Region<'tcx>,
214 );
215
216 fn push_verify(
217 &mut self,
218 origin: SubregionOrigin<'tcx>,
219 kind: GenericKind<'tcx>,
220 a: ty::Region<'tcx>,
221 bound: VerifyBound<'tcx>,
222 );
223}
224
dc9dc135 225impl<'cx, 'tcx, D> TypeOutlives<'cx, 'tcx, D>
8faf50e0
XL
226where
227 D: TypeOutlivesDelegate<'tcx>,
228{
229 pub fn new(
230 delegate: D,
dc9dc135 231 tcx: TyCtxt<'tcx>,
0bf4aa26 232 region_bound_pairs: &'cx RegionBoundPairs<'tcx>,
abe05a73
XL
233 implicit_region_bound: Option<ty::Region<'tcx>>,
234 param_env: ty::ParamEnv<'tcx>,
235 ) -> Self {
236 Self {
8faf50e0
XL
237 delegate,
238 tcx,
0bf4aa26
XL
239 verify_bound: VerifyBoundCx::new(
240 tcx,
241 region_bound_pairs,
242 implicit_region_bound,
243 param_env,
244 ),
abe05a73
XL
245 }
246 }
247
248 /// Adds constraints to inference such that `T: 'a` holds (or
249 /// reports an error if it cannot).
250 ///
251 /// # Parameters
252 ///
253 /// - `origin`, the reason we need this constraint
254 /// - `ty`, the type `T`
255 /// - `region`, the region `'a`
8faf50e0
XL
256 pub fn type_must_outlive(
257 &mut self,
abe05a73
XL
258 origin: infer::SubregionOrigin<'tcx>,
259 ty: Ty<'tcx>,
260 region: ty::Region<'tcx>,
261 ) {
dfeec247 262 debug!("type_must_outlive(ty={:?}, region={:?}, origin={:?})", ty, region, origin);
abe05a73 263
a1dfa0c6 264 assert!(!ty.has_escaping_bound_vars());
abe05a73 265
a1dfa0c6
XL
266 let mut components = smallvec![];
267 self.tcx.push_outlives_components(ty, &mut components);
268 self.components_must_outlive(origin, &components, region);
abe05a73
XL
269 }
270
abe05a73 271 fn components_must_outlive(
8faf50e0 272 &mut self,
abe05a73 273 origin: infer::SubregionOrigin<'tcx>,
a1dfa0c6 274 components: &[Component<'tcx>],
abe05a73
XL
275 region: ty::Region<'tcx>,
276 ) {
a1dfa0c6 277 for component in components.iter() {
abe05a73
XL
278 let origin = origin.clone();
279 match component {
280 Component::Region(region1) => {
dfeec247 281 self.delegate.push_sub_region_constraint(origin, region, region1);
abe05a73
XL
282 }
283 Component::Param(param_ty) => {
a1dfa0c6 284 self.param_ty_must_outlive(origin, region, *param_ty);
abe05a73
XL
285 }
286 Component::Projection(projection_ty) => {
a1dfa0c6 287 self.projection_must_outlive(origin, region, *projection_ty);
abe05a73
XL
288 }
289 Component::EscapingProjection(subcomponents) => {
a1dfa0c6 290 self.components_must_outlive(origin, &subcomponents, region);
abe05a73
XL
291 }
292 Component::UnresolvedInferenceVariable(v) => {
293 // ignore this, we presume it will yield an error
294 // later, since if a type variable is not resolved by
295 // this point it never will be
8faf50e0 296 self.tcx.sess.delay_span_bug(
abe05a73
XL
297 origin.span(),
298 &format!("unresolved inference variable in outlives: {:?}", v),
299 );
300 }
301 }
302 }
303 }
304
305 fn param_ty_must_outlive(
8faf50e0 306 &mut self,
abe05a73
XL
307 origin: infer::SubregionOrigin<'tcx>,
308 region: ty::Region<'tcx>,
309 param_ty: ty::ParamTy,
310 ) {
311 debug!(
312 "param_ty_must_outlive(region={:?}, param_ty={:?}, origin={:?})",
8faf50e0 313 region, param_ty, origin
abe05a73
XL
314 );
315
abe05a73 316 let generic = GenericKind::Param(param_ty);
0bf4aa26 317 let verify_bound = self.verify_bound.generic_bound(generic);
dfeec247 318 self.delegate.push_verify(origin, generic, region, verify_bound);
abe05a73
XL
319 }
320
321 fn projection_must_outlive(
8faf50e0 322 &mut self,
abe05a73
XL
323 origin: infer::SubregionOrigin<'tcx>,
324 region: ty::Region<'tcx>,
325 projection_ty: ty::ProjectionTy<'tcx>,
326 ) {
327 debug!(
328 "projection_must_outlive(region={:?}, projection_ty={:?}, origin={:?})",
8faf50e0 329 region, projection_ty, origin
abe05a73
XL
330 );
331
332 // This case is thorny for inference. The fundamental problem is
333 // that there are many cases where we have choice, and inference
334 // doesn't like choice (the current region inference in
335 // particular). :) First off, we have to choose between using the
336 // OutlivesProjectionEnv, OutlivesProjectionTraitDef, and
337 // OutlivesProjectionComponent rules, any one of which is
338 // sufficient. If there are no inference variables involved, it's
339 // not hard to pick the right rule, but if there are, we're in a
340 // bit of a catch 22: if we picked which rule we were going to
341 // use, we could add constraints to the region inference graph
342 // that make it apply, but if we don't add those constraints, the
343 // rule might not apply (but another rule might). For now, we err
344 // on the side of adding too few edges into the graph.
345
13cf67c4
XL
346 // Compute the bounds we can derive from the trait definition.
347 // These are guaranteed to apply, no matter the inference
348 // results.
dfeec247
XL
349 let trait_bounds: Vec<_> =
350 self.verify_bound.projection_declared_bounds_from_trait(projection_ty).collect();
13cf67c4 351
0bf4aa26
XL
352 // Compute the bounds we can derive from the environment. This
353 // is an "approximate" match -- in some cases, these bounds
354 // may not apply.
dfeec247
XL
355 let mut approx_env_bounds =
356 self.verify_bound.projection_approx_declared_bounds_from_env(projection_ty);
357 debug!("projection_must_outlive: approx_env_bounds={:?}", approx_env_bounds);
abe05a73 358
13cf67c4
XL
359 // Remove outlives bounds that we get from the environment but
360 // which are also deducable from the trait. This arises (cc
0731742a 361 // #55756) in cases where you have e.g., `<T as Foo<'a>>::Item:
13cf67c4
XL
362 // 'a` in the environment but `trait Foo<'b> { type Item: 'b
363 // }` in the trait definition.
1b1a35ee 364 approx_env_bounds.retain(|bound| match *bound.0.kind() {
dfeec247
XL
365 ty::Projection(projection_ty) => self
366 .verify_bound
367 .projection_declared_bounds_from_trait(projection_ty)
368 .all(|r| r != bound.1),
13cf67c4 369
dfeec247 370 _ => panic!("expected only projection types from env, not {:?}", bound.0),
13cf67c4 371 });
abe05a73
XL
372
373 // If declared bounds list is empty, the only applicable rule is
374 // OutlivesProjectionComponent. If there are inference variables,
375 // then, we can break down the outlives into more primitive
376 // components without adding unnecessary edges.
377 //
378 // If there are *no* inference variables, however, we COULD do
379 // this, but we choose not to, because the error messages are less
380 // good. For example, a requirement like `T::Item: 'r` would be
381 // translated to a requirement that `T: 'r`; when this is reported
382 // to the user, it will thus say "T: 'r must hold so that T::Item:
383 // 'r holds". But that makes it sound like the only way to fix
384 // the problem is to add `T: 'r`, which isn't true. So, if there are no
385 // inference variables, we use a verify constraint instead of adding
386 // edges, which winds up enforcing the same condition.
387 let needs_infer = projection_ty.needs_infer();
0bf4aa26 388 if approx_env_bounds.is_empty() && trait_bounds.is_empty() && needs_infer {
abe05a73
XL
389 debug!("projection_must_outlive: no declared bounds");
390
532ac7d7
XL
391 for k in projection_ty.substs {
392 match k.unpack() {
e74abb32 393 GenericArgKind::Lifetime(lt) => {
532ac7d7
XL
394 self.delegate.push_sub_region_constraint(origin.clone(), region, lt);
395 }
e74abb32 396 GenericArgKind::Type(ty) => {
532ac7d7
XL
397 self.type_must_outlive(origin.clone(), ty, region);
398 }
e74abb32 399 GenericArgKind::Const(_) => {
532ac7d7
XL
400 // Const parameters don't impose constraints.
401 }
402 }
abe05a73
XL
403 }
404
405 return;
406 }
407
0bf4aa26
XL
408 // If we found a unique bound `'b` from the trait, and we
409 // found nothing else from the environment, then the best
410 // action is to require that `'b: 'r`, so do that.
411 //
412 // This is best no matter what rule we use:
abe05a73 413 //
0bf4aa26
XL
414 // - OutlivesProjectionEnv: these would translate to the requirement that `'b:'r`
415 // - OutlivesProjectionTraitDef: these would translate to the requirement that `'b:'r`
416 // - OutlivesProjectionComponent: this would require `'b:'r`
417 // in addition to other conditions
418 if !trait_bounds.is_empty()
419 && trait_bounds[1..]
420 .iter()
421 .chain(approx_env_bounds.iter().map(|b| &b.1))
422 .all(|b| *b == trait_bounds[0])
423 {
424 let unique_bound = trait_bounds[0];
dfeec247 425 debug!("projection_must_outlive: unique trait bound = {:?}", unique_bound);
0bf4aa26 426 debug!("projection_must_outlive: unique declared bound appears in trait ref");
dfeec247 427 self.delegate.push_sub_region_constraint(origin, region, unique_bound);
0bf4aa26 428 return;
abe05a73
XL
429 }
430
431 // Fallback to verifying after the fact that there exists a
432 // declared bound, or that all the components appearing in the
433 // projection outlive; in some cases, this may add insufficient
434 // edges into the inference graph, leading to inference failures
435 // even though a satisfactory solution exists.
abe05a73 436 let generic = GenericKind::Projection(projection_ty);
0bf4aa26 437 let verify_bound = self.verify_bound.generic_bound(generic);
ba9703b0 438 self.delegate.push_verify(origin, generic, region, verify_bound);
abe05a73 439 }
abe05a73 440}
8faf50e0 441
dc9dc135 442impl<'cx, 'tcx> TypeOutlivesDelegate<'tcx> for &'cx InferCtxt<'cx, 'tcx> {
8faf50e0
XL
443 fn push_sub_region_constraint(
444 &mut self,
445 origin: SubregionOrigin<'tcx>,
446 a: ty::Region<'tcx>,
447 b: ty::Region<'tcx>,
448 ) {
449 self.sub_regions(origin, a, b)
450 }
451
452 fn push_verify(
453 &mut self,
454 origin: SubregionOrigin<'tcx>,
455 kind: GenericKind<'tcx>,
456 a: ty::Region<'tcx>,
457 bound: VerifyBound<'tcx>,
458 ) {
459 self.verify_generic_bound(origin, kind, a, bound)
460 }
461}