]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/outlives/obligations.rs
0ae4446ee63faf5044938b5a9d2bf554cbc54cad
[rust.git] / src / librustc / infer / outlives / obligations.rs
1 //! Code that handles "type-outlives" constraints like `T: 'a`. This
2 //! is based on the `push_outlives_components` function defined on the tcx,
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 //!
58 //! the type of the closure's first argument would be `&'a ?U`. We
59 //! might later infer `?U` to something like `&'b u32`, which would
60 //! imply that `'b: 'a`.
61
62 use crate::infer::outlives::env::RegionBoundPairs;
63 use crate::infer::outlives::verify::VerifyBoundCx;
64 use crate::infer::{self, GenericKind, InferCtxt, RegionObligation, SubregionOrigin, VerifyBound};
65 use rustc_data_structures::fx::FxHashMap;
66 use crate::hir;
67 use crate::traits::ObligationCause;
68 use crate::ty::outlives::Component;
69 use crate::ty::{self, Region, Ty, TyCtxt, TypeFoldable};
70 use crate::ty::subst::UnpackedKind;
71
72 impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
73     /// Registers that the given region obligation must be resolved
74     /// from within the scope of `body_id`. These regions are enqueued
75     /// and later processed by regionck, when full type information is
76     /// available (see `region_obligations` field for more
77     /// information).
78     pub fn register_region_obligation(
79         &self,
80         body_id: hir::HirId,
81         obligation: RegionObligation<'tcx>,
82     ) {
83         debug!(
84             "register_region_obligation(body_id={:?}, obligation={:?})",
85             body_id, obligation
86         );
87
88         self.region_obligations
89             .borrow_mut()
90             .push((body_id, obligation));
91     }
92
93     pub fn register_region_obligation_with_cause(
94         &self,
95         sup_type: Ty<'tcx>,
96         sub_region: Region<'tcx>,
97         cause: &ObligationCause<'tcx>,
98     ) {
99         let origin = SubregionOrigin::from_obligation_cause(cause, || {
100             infer::RelateParamBound(cause.span, sup_type)
101         });
102
103         self.register_region_obligation(
104             cause.body_id,
105             RegionObligation {
106                 sup_type,
107                 sub_region,
108                 origin,
109             },
110         );
111     }
112
113     /// Trait queries just want to pass back type obligations "as is"
114     pub fn take_registered_region_obligations(&self) -> Vec<(hir::HirId, RegionObligation<'tcx>)> {
115         ::std::mem::replace(&mut *self.region_obligations.borrow_mut(), vec![])
116     }
117
118     /// Process the region obligations that must be proven (during
119     /// `regionck`) for the given `body_id`, given information about
120     /// the region bounds in scope and so forth. This function must be
121     /// invoked for all relevant body-ids before region inference is
122     /// done (or else an assert will fire).
123     ///
124     /// See the `region_obligations` field of `InferCtxt` for some
125     /// comments about how this function fits into the overall expected
126     /// flow of the inferencer. The key point is that it is
127     /// invoked after all type-inference variables have been bound --
128     /// towards the end of regionck. This also ensures that the
129     /// region-bound-pairs are available (see comments above regarding
130     /// closures).
131     ///
132     /// # Parameters
133     ///
134     /// - `region_bound_pairs`: the set of region bounds implied by
135     ///   the parameters and where-clauses. In particular, each pair
136     ///   `('a, K)` in this list tells us that the bounds in scope
137     ///   indicate that `K: 'a`, where `K` is either a generic
138     ///   parameter like `T` or a projection like `T::Item`.
139     /// - `implicit_region_bound`: if some, this is a region bound
140     ///   that is considered to hold for all type parameters (the
141     ///   function body).
142     /// - `param_env` is the parameter environment for the enclosing function.
143     /// - `body_id` is the body-id whose region obligations are being
144     ///   processed.
145     ///
146     /// # Returns
147     ///
148     /// This function may have to perform normalizations, and hence it
149     /// returns an `InferOk` with subobligations that must be
150     /// processed.
151     pub fn process_registered_region_obligations(
152         &self,
153         region_bound_pairs_map: &FxHashMap<hir::HirId, RegionBoundPairs<'tcx>>,
154         implicit_region_bound: Option<ty::Region<'tcx>>,
155         param_env: ty::ParamEnv<'tcx>,
156     ) {
157         assert!(
158             !self.in_snapshot.get(),
159             "cannot process registered region obligations in a snapshot"
160         );
161
162         debug!("process_registered_region_obligations()");
163
164         let my_region_obligations = self.take_registered_region_obligations();
165
166         for (
167             body_id,
168             RegionObligation {
169                 sup_type,
170                 sub_region,
171                 origin,
172             },
173         ) in my_region_obligations
174         {
175             debug!(
176                 "process_registered_region_obligations: sup_type={:?} sub_region={:?} origin={:?}",
177                 sup_type, sub_region, origin
178             );
179
180             let sup_type = self.resolve_vars_if_possible(&sup_type);
181
182             if let Some(region_bound_pairs) = region_bound_pairs_map.get(&body_id) {
183                 let outlives = &mut TypeOutlives::new(
184                     self,
185                     self.tcx,
186                     &region_bound_pairs,
187                     implicit_region_bound,
188                     param_env,
189                 );
190                 outlives.type_must_outlive(origin, sup_type, sub_region);
191             } else {
192                 self.tcx.sess.delay_span_bug(
193                     origin.span(),
194                     &format!("no region-bound-pairs for {:?}", body_id),
195                 )
196             }
197         }
198     }
199
200     /// Processes a single ad-hoc region obligation that was not
201     /// registered in advance.
202     pub fn type_must_outlive(
203         &self,
204         region_bound_pairs: &RegionBoundPairs<'tcx>,
205         implicit_region_bound: Option<ty::Region<'tcx>>,
206         param_env: ty::ParamEnv<'tcx>,
207         origin: infer::SubregionOrigin<'tcx>,
208         ty: Ty<'tcx>,
209         region: ty::Region<'tcx>,
210     ) {
211         let outlives = &mut TypeOutlives::new(
212             self,
213             self.tcx,
214             region_bound_pairs,
215             implicit_region_bound,
216             param_env,
217         );
218         let ty = self.resolve_vars_if_possible(&ty);
219         outlives.type_must_outlive(origin, ty, region);
220     }
221 }
222
223 /// The `TypeOutlives` struct has the job of "lowering" a `T: 'a`
224 /// obligation into a series of `'a: 'b` constraints and "verifys", as
225 /// described on the module comment. The final constraints are emitted
226 /// via a "delegate" of type `D` -- this is usually the `infcx`, which
227 /// accrues them into the `region_obligations` code, but for NLL we
228 /// use something else.
229 pub struct TypeOutlives<'cx, 'tcx, D>
230 where
231     D: TypeOutlivesDelegate<'tcx>,
232 {
233     // See the comments on `process_registered_region_obligations` for the meaning
234     // of these fields.
235     delegate: D,
236     tcx: TyCtxt<'tcx>,
237     verify_bound: VerifyBoundCx<'cx, 'tcx>,
238 }
239
240 pub trait TypeOutlivesDelegate<'tcx> {
241     fn push_sub_region_constraint(
242         &mut self,
243         origin: SubregionOrigin<'tcx>,
244         a: ty::Region<'tcx>,
245         b: ty::Region<'tcx>,
246     );
247
248     fn push_verify(
249         &mut self,
250         origin: SubregionOrigin<'tcx>,
251         kind: GenericKind<'tcx>,
252         a: ty::Region<'tcx>,
253         bound: VerifyBound<'tcx>,
254     );
255 }
256
257 impl<'cx, 'tcx, D> TypeOutlives<'cx, 'tcx, D>
258 where
259     D: TypeOutlivesDelegate<'tcx>,
260 {
261     pub fn new(
262         delegate: D,
263         tcx: TyCtxt<'tcx>,
264         region_bound_pairs: &'cx RegionBoundPairs<'tcx>,
265         implicit_region_bound: Option<ty::Region<'tcx>>,
266         param_env: ty::ParamEnv<'tcx>,
267     ) -> Self {
268         Self {
269             delegate,
270             tcx,
271             verify_bound: VerifyBoundCx::new(
272                 tcx,
273                 region_bound_pairs,
274                 implicit_region_bound,
275                 param_env,
276             ),
277         }
278     }
279
280     /// Adds constraints to inference such that `T: 'a` holds (or
281     /// reports an error if it cannot).
282     ///
283     /// # Parameters
284     ///
285     /// - `origin`, the reason we need this constraint
286     /// - `ty`, the type `T`
287     /// - `region`, the region `'a`
288     pub fn type_must_outlive(
289         &mut self,
290         origin: infer::SubregionOrigin<'tcx>,
291         ty: Ty<'tcx>,
292         region: ty::Region<'tcx>,
293     ) {
294         debug!(
295             "type_must_outlive(ty={:?}, region={:?}, origin={:?})",
296             ty, region, origin
297         );
298
299         assert!(!ty.has_escaping_bound_vars());
300
301         let mut components = smallvec![];
302         self.tcx.push_outlives_components(ty, &mut components);
303         self.components_must_outlive(origin, &components, region);
304     }
305
306     fn components_must_outlive(
307         &mut self,
308         origin: infer::SubregionOrigin<'tcx>,
309         components: &[Component<'tcx>],
310         region: ty::Region<'tcx>,
311     ) {
312         for component in components.iter() {
313             let origin = origin.clone();
314             match component {
315                 Component::Region(region1) => {
316                     self.delegate
317                         .push_sub_region_constraint(origin, region, region1);
318                 }
319                 Component::Param(param_ty) => {
320                     self.param_ty_must_outlive(origin, region, *param_ty);
321                 }
322                 Component::Projection(projection_ty) => {
323                     self.projection_must_outlive(origin, region, *projection_ty);
324                 }
325                 Component::EscapingProjection(subcomponents) => {
326                     self.components_must_outlive(origin, &subcomponents, region);
327                 }
328                 Component::UnresolvedInferenceVariable(v) => {
329                     // ignore this, we presume it will yield an error
330                     // later, since if a type variable is not resolved by
331                     // this point it never will be
332                     self.tcx.sess.delay_span_bug(
333                         origin.span(),
334                         &format!("unresolved inference variable in outlives: {:?}", v),
335                     );
336                 }
337             }
338         }
339     }
340
341     fn param_ty_must_outlive(
342         &mut self,
343         origin: infer::SubregionOrigin<'tcx>,
344         region: ty::Region<'tcx>,
345         param_ty: ty::ParamTy,
346     ) {
347         debug!(
348             "param_ty_must_outlive(region={:?}, param_ty={:?}, origin={:?})",
349             region, param_ty, origin
350         );
351
352         let generic = GenericKind::Param(param_ty);
353         let verify_bound = self.verify_bound.generic_bound(generic);
354         self.delegate
355             .push_verify(origin, generic, region, verify_bound);
356     }
357
358     fn projection_must_outlive(
359         &mut self,
360         origin: infer::SubregionOrigin<'tcx>,
361         region: ty::Region<'tcx>,
362         projection_ty: ty::ProjectionTy<'tcx>,
363     ) {
364         debug!(
365             "projection_must_outlive(region={:?}, projection_ty={:?}, origin={:?})",
366             region, projection_ty, origin
367         );
368
369         // This case is thorny for inference. The fundamental problem is
370         // that there are many cases where we have choice, and inference
371         // doesn't like choice (the current region inference in
372         // particular). :) First off, we have to choose between using the
373         // OutlivesProjectionEnv, OutlivesProjectionTraitDef, and
374         // OutlivesProjectionComponent rules, any one of which is
375         // sufficient.  If there are no inference variables involved, it's
376         // not hard to pick the right rule, but if there are, we're in a
377         // bit of a catch 22: if we picked which rule we were going to
378         // use, we could add constraints to the region inference graph
379         // that make it apply, but if we don't add those constraints, the
380         // rule might not apply (but another rule might). For now, we err
381         // on the side of adding too few edges into the graph.
382
383         // Compute the bounds we can derive from the trait definition.
384         // These are guaranteed to apply, no matter the inference
385         // results.
386         let trait_bounds: Vec<_> = self.verify_bound
387             .projection_declared_bounds_from_trait(projection_ty)
388             .collect();
389
390         // Compute the bounds we can derive from the environment. This
391         // is an "approximate" match -- in some cases, these bounds
392         // may not apply.
393         let mut approx_env_bounds = self.verify_bound
394             .projection_approx_declared_bounds_from_env(projection_ty);
395         debug!(
396             "projection_must_outlive: approx_env_bounds={:?}",
397             approx_env_bounds
398         );
399
400         // Remove outlives bounds that we get from the environment but
401         // which are also deducable from the trait. This arises (cc
402         // #55756) in cases where you have e.g., `<T as Foo<'a>>::Item:
403         // 'a` in the environment but `trait Foo<'b> { type Item: 'b
404         // }` in the trait definition.
405         approx_env_bounds.retain(|bound| {
406             match bound.0.sty {
407                 ty::Projection(projection_ty) => {
408                     self.verify_bound.projection_declared_bounds_from_trait(projection_ty)
409                         .all(|r| r != bound.1)
410                 }
411
412                 _ => panic!("expected only projection types from env, not {:?}", bound.0),
413             }
414         });
415
416         // If declared bounds list is empty, the only applicable rule is
417         // OutlivesProjectionComponent. If there are inference variables,
418         // then, we can break down the outlives into more primitive
419         // components without adding unnecessary edges.
420         //
421         // If there are *no* inference variables, however, we COULD do
422         // this, but we choose not to, because the error messages are less
423         // good. For example, a requirement like `T::Item: 'r` would be
424         // translated to a requirement that `T: 'r`; when this is reported
425         // to the user, it will thus say "T: 'r must hold so that T::Item:
426         // 'r holds". But that makes it sound like the only way to fix
427         // the problem is to add `T: 'r`, which isn't true. So, if there are no
428         // inference variables, we use a verify constraint instead of adding
429         // edges, which winds up enforcing the same condition.
430         let needs_infer = projection_ty.needs_infer();
431         if approx_env_bounds.is_empty() && trait_bounds.is_empty() && needs_infer {
432             debug!("projection_must_outlive: no declared bounds");
433
434             for k in projection_ty.substs {
435                 match k.unpack() {
436                     UnpackedKind::Lifetime(lt) => {
437                         self.delegate.push_sub_region_constraint(origin.clone(), region, lt);
438                     }
439                     UnpackedKind::Type(ty) => {
440                         self.type_must_outlive(origin.clone(), ty, region);
441                     }
442                     UnpackedKind::Const(_) => {
443                         // Const parameters don't impose constraints.
444                     }
445                 }
446             }
447
448             return;
449         }
450
451         // If we found a unique bound `'b` from the trait, and we
452         // found nothing else from the environment, then the best
453         // action is to require that `'b: 'r`, so do that.
454         //
455         // This is best no matter what rule we use:
456         //
457         // - OutlivesProjectionEnv: these would translate to the requirement that `'b:'r`
458         // - OutlivesProjectionTraitDef: these would translate to the requirement that `'b:'r`
459         // - OutlivesProjectionComponent: this would require `'b:'r`
460         //   in addition to other conditions
461         if !trait_bounds.is_empty()
462             && trait_bounds[1..]
463                 .iter()
464                 .chain(approx_env_bounds.iter().map(|b| &b.1))
465                 .all(|b| *b == trait_bounds[0])
466         {
467             let unique_bound = trait_bounds[0];
468             debug!(
469                 "projection_must_outlive: unique trait bound = {:?}",
470                 unique_bound
471             );
472             debug!("projection_must_outlive: unique declared bound appears in trait ref");
473             self.delegate
474                 .push_sub_region_constraint(origin, region, unique_bound);
475             return;
476         }
477
478         // Fallback to verifying after the fact that there exists a
479         // declared bound, or that all the components appearing in the
480         // projection outlive; in some cases, this may add insufficient
481         // edges into the inference graph, leading to inference failures
482         // even though a satisfactory solution exists.
483         let generic = GenericKind::Projection(projection_ty);
484         let verify_bound = self.verify_bound.generic_bound(generic);
485         self.delegate
486             .push_verify(origin, generic.clone(), region, verify_bound);
487     }
488 }
489
490 impl<'cx, 'tcx> TypeOutlivesDelegate<'tcx> for &'cx InferCtxt<'cx, 'tcx> {
491     fn push_sub_region_constraint(
492         &mut self,
493         origin: SubregionOrigin<'tcx>,
494         a: ty::Region<'tcx>,
495         b: ty::Region<'tcx>,
496     ) {
497         self.sub_regions(origin, a, b)
498     }
499
500     fn push_verify(
501         &mut self,
502         origin: SubregionOrigin<'tcx>,
503         kind: GenericKind<'tcx>,
504         a: ty::Region<'tcx>,
505         bound: VerifyBound<'tcx>,
506     ) {
507         self.verify_generic_bound(origin, kind, a, bound)
508     }
509 }