]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/region_infer/mod.rs
Changes the type `mir::Mir` into `mir::Body`
[rust.git] / src / librustc_mir / borrow_check / nll / region_infer / mod.rs
1 use super::universal_regions::UniversalRegions;
2 use crate::borrow_check::nll::constraints::graph::NormalConstraintGraph;
3 use crate::borrow_check::nll::constraints::{ConstraintSccIndex, ConstraintSet, OutlivesConstraint};
4 use crate::borrow_check::nll::region_infer::values::{
5     PlaceholderIndices, RegionElement, ToElementIndex
6 };
7 use crate::borrow_check::Upvar;
8 use crate::borrow_check::nll::type_check::free_region_relations::UniversalRegionRelations;
9 use crate::borrow_check::nll::type_check::Locations;
10 use rustc::hir::def_id::DefId;
11 use rustc::infer::canonical::QueryRegionConstraint;
12 use rustc::infer::region_constraints::{GenericKind, VarInfos, VerifyBound};
13 use rustc::infer::{InferCtxt, NLLRegionVariableOrigin, RegionVariableOrigin};
14 use rustc::mir::{
15     ClosureOutlivesRequirement, ClosureOutlivesSubject, ClosureRegionRequirements,
16     ConstraintCategory, Local, Location, Body,
17 };
18 use rustc::ty::{self, subst::SubstsRef, RegionVid, Ty, TyCtxt, TypeFoldable};
19 use rustc::util::common::{self, ErrorReported};
20 use rustc_data_structures::bit_set::BitSet;
21 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
22 use rustc_data_structures::graph::scc::Sccs;
23 use rustc_data_structures::indexed_vec::IndexVec;
24 use rustc_errors::{Diagnostic, DiagnosticBuilder};
25 use syntax_pos::Span;
26
27 use std::rc::Rc;
28
29 mod dump_mir;
30 mod error_reporting;
31 crate use self::error_reporting::{RegionName, RegionNameSource};
32 mod graphviz;
33 pub mod values;
34 use self::values::{LivenessValues, RegionValueElements, RegionValues};
35
36 use super::ToRegionVid;
37
38 pub struct RegionInferenceContext<'tcx> {
39     /// Contains the definition for every region variable. Region
40     /// variables are identified by their index (`RegionVid`). The
41     /// definition contains information about where the region came
42     /// from as well as its final inferred value.
43     definitions: IndexVec<RegionVid, RegionDefinition<'tcx>>,
44
45     /// The liveness constraints added to each region. For most
46     /// regions, these start out empty and steadily grow, though for
47     /// each universally quantified region R they start out containing
48     /// the entire CFG and `end(R)`.
49     liveness_constraints: LivenessValues<RegionVid>,
50
51     /// The outlives constraints computed by the type-check.
52     constraints: Rc<ConstraintSet>,
53
54     /// The constraint-set, but in graph form, making it easy to traverse
55     /// the constraints adjacent to a particular region. Used to construct
56     /// the SCC (see `constraint_sccs`) and for error reporting.
57     constraint_graph: Rc<NormalConstraintGraph>,
58
59     /// The SCC computed from `constraints` and the constraint graph. Used to
60     /// compute the values of each region.
61     constraint_sccs: Rc<Sccs<RegionVid, ConstraintSccIndex>>,
62
63     /// Map closure bounds to a `Span` that should be used for error reporting.
64     closure_bounds_mapping:
65         FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
66
67     /// Contains the minimum universe of any variable within the same
68     /// SCC. We will ensure that no SCC contains values that are not
69     /// visible from this index.
70     scc_universes: IndexVec<ConstraintSccIndex, ty::UniverseIndex>,
71
72     /// Contains a "representative" from each SCC. This will be the
73     /// minimal RegionVid belonging to that universe. It is used as a
74     /// kind of hacky way to manage checking outlives relationships,
75     /// since we can 'canonicalize' each region to the representative
76     /// of its SCC and be sure that -- if they have the same repr --
77     /// they *must* be equal (though not having the same repr does not
78     /// mean they are unequal).
79     scc_representatives: IndexVec<ConstraintSccIndex, ty::RegionVid>,
80
81     /// The final inferred values of the region variables; we compute
82     /// one value per SCC. To get the value for any given *region*,
83     /// you first find which scc it is a part of.
84     scc_values: RegionValues<ConstraintSccIndex>,
85
86     /// Type constraints that we check after solving.
87     type_tests: Vec<TypeTest<'tcx>>,
88
89     /// Information about the universally quantified regions in scope
90     /// on this function.
91     universal_regions: Rc<UniversalRegions<'tcx>>,
92
93     /// Information about how the universally quantified regions in
94     /// scope on this function relate to one another.
95     universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
96 }
97
98 struct RegionDefinition<'tcx> {
99     /// What kind of variable is this -- a free region? existential
100     /// variable? etc. (See the `NLLRegionVariableOrigin` for more
101     /// info.)
102     origin: NLLRegionVariableOrigin,
103
104     /// Which universe is this region variable defined in? This is
105     /// most often `ty::UniverseIndex::ROOT`, but when we encounter
106     /// forall-quantifiers like `for<'a> { 'a = 'b }`, we would create
107     /// the variable for `'a` in a fresh universe that extends ROOT.
108     universe: ty::UniverseIndex,
109
110     /// If this is 'static or an early-bound region, then this is
111     /// `Some(X)` where `X` is the name of the region.
112     external_name: Option<ty::Region<'tcx>>,
113 }
114
115 /// N.B., the variants in `Cause` are intentionally ordered. Lower
116 /// values are preferred when it comes to error messages. Do not
117 /// reorder willy nilly.
118 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
119 pub(crate) enum Cause {
120     /// point inserted because Local was live at the given Location
121     LiveVar(Local, Location),
122
123     /// point inserted because Local was dropped at the given Location
124     DropVar(Local, Location),
125 }
126
127 /// A "type test" corresponds to an outlives constraint between a type
128 /// and a lifetime, like `T: 'x` or `<T as Foo>::Bar: 'x`. They are
129 /// translated from the `Verify` region constraints in the ordinary
130 /// inference context.
131 ///
132 /// These sorts of constraints are handled differently than ordinary
133 /// constraints, at least at present. During type checking, the
134 /// `InferCtxt::process_registered_region_obligations` method will
135 /// attempt to convert a type test like `T: 'x` into an ordinary
136 /// outlives constraint when possible (for example, `&'a T: 'b` will
137 /// be converted into `'a: 'b` and registered as a `Constraint`).
138 ///
139 /// In some cases, however, there are outlives relationships that are
140 /// not converted into a region constraint, but rather into one of
141 /// these "type tests". The distinction is that a type test does not
142 /// influence the inference result, but instead just examines the
143 /// values that we ultimately inferred for each region variable and
144 /// checks that they meet certain extra criteria. If not, an error
145 /// can be issued.
146 ///
147 /// One reason for this is that these type tests typically boil down
148 /// to a check like `'a: 'x` where `'a` is a universally quantified
149 /// region -- and therefore not one whose value is really meant to be
150 /// *inferred*, precisely (this is not always the case: one can have a
151 /// type test like `<Foo as Trait<'?0>>::Bar: 'x`, where `'?0` is an
152 /// inference variable). Another reason is that these type tests can
153 /// involve *disjunction* -- that is, they can be satisfied in more
154 /// than one way.
155 ///
156 /// For more information about this translation, see
157 /// `InferCtxt::process_registered_region_obligations` and
158 /// `InferCtxt::type_must_outlive` in `rustc::infer::outlives`.
159 #[derive(Clone, Debug)]
160 pub struct TypeTest<'tcx> {
161     /// The type `T` that must outlive the region.
162     pub generic_kind: GenericKind<'tcx>,
163
164     /// The region `'x` that the type must outlive.
165     pub lower_bound: RegionVid,
166
167     /// Where did this constraint arise and why?
168     pub locations: Locations,
169
170     /// A test which, if met by the region `'x`, proves that this type
171     /// constraint is satisfied.
172     pub verify_bound: VerifyBound<'tcx>,
173 }
174
175 impl<'tcx> RegionInferenceContext<'tcx> {
176     /// Creates a new region inference context with a total of
177     /// `num_region_variables` valid inference variables; the first N
178     /// of those will be constant regions representing the free
179     /// regions defined in `universal_regions`.
180     ///
181     /// The `outlives_constraints` and `type_tests` are an initial set
182     /// of constraints produced by the MIR type check.
183     pub(crate) fn new(
184         var_infos: VarInfos,
185         universal_regions: Rc<UniversalRegions<'tcx>>,
186         placeholder_indices: Rc<PlaceholderIndices>,
187         universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
188         _mir: &Body<'tcx>,
189         outlives_constraints: ConstraintSet,
190         closure_bounds_mapping: FxHashMap<
191             Location,
192             FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>,
193         >,
194         type_tests: Vec<TypeTest<'tcx>>,
195         liveness_constraints: LivenessValues<RegionVid>,
196         elements: &Rc<RegionValueElements>,
197     ) -> Self {
198         // Create a RegionDefinition for each inference variable.
199         let definitions: IndexVec<_, _> = var_infos
200             .into_iter()
201             .map(|info| RegionDefinition::new(info.universe, info.origin))
202             .collect();
203
204         let constraints = Rc::new(outlives_constraints); // freeze constraints
205         let constraint_graph = Rc::new(constraints.graph(definitions.len()));
206         let fr_static = universal_regions.fr_static;
207         let constraint_sccs = Rc::new(constraints.compute_sccs(&constraint_graph, fr_static));
208
209         let mut scc_values =
210             RegionValues::new(elements, universal_regions.len(), &placeholder_indices);
211
212         for region in liveness_constraints.rows() {
213             let scc = constraint_sccs.scc(region);
214             scc_values.merge_liveness(scc, region, &liveness_constraints);
215         }
216
217         let scc_universes = Self::compute_scc_universes(&constraint_sccs, &definitions);
218
219         let scc_representatives = Self::compute_scc_representatives(&constraint_sccs, &definitions);
220
221         let mut result = Self {
222             definitions,
223             liveness_constraints,
224             constraints,
225             constraint_graph,
226             constraint_sccs,
227             closure_bounds_mapping,
228             scc_universes,
229             scc_representatives,
230             scc_values,
231             type_tests,
232             universal_regions,
233             universal_region_relations,
234         };
235
236         result.init_free_and_bound_regions();
237
238         result
239     }
240
241     /// Each SCC is the combination of many region variables which
242     /// have been equated. Therefore, we can associate a universe with
243     /// each SCC which is minimum of all the universes of its
244     /// constituent regions -- this is because whatever value the SCC
245     /// takes on must be a value that each of the regions within the
246     /// SCC could have as well. This implies that the SCC must have
247     /// the minimum, or narrowest, universe.
248     fn compute_scc_universes(
249         constraints_scc: &Sccs<RegionVid, ConstraintSccIndex>,
250         definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
251     ) -> IndexVec<ConstraintSccIndex, ty::UniverseIndex> {
252         let num_sccs = constraints_scc.num_sccs();
253         let mut scc_universes = IndexVec::from_elem_n(ty::UniverseIndex::MAX, num_sccs);
254
255         for (region_vid, region_definition) in definitions.iter_enumerated() {
256             let scc = constraints_scc.scc(region_vid);
257             let scc_universe = &mut scc_universes[scc];
258             *scc_universe = ::std::cmp::min(*scc_universe, region_definition.universe);
259         }
260
261         debug!("compute_scc_universes: scc_universe = {:#?}", scc_universes);
262
263         scc_universes
264     }
265
266     /// For each SCC, we compute a unique `RegionVid` (in fact, the
267     /// minimal one that belongs to the SCC). See
268     /// `scc_representatives` field of `RegionInferenceContext` for
269     /// more details.
270     fn compute_scc_representatives(
271         constraints_scc: &Sccs<RegionVid, ConstraintSccIndex>,
272         definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
273     ) -> IndexVec<ConstraintSccIndex, ty::RegionVid> {
274         let num_sccs = constraints_scc.num_sccs();
275         let next_region_vid = definitions.next_index();
276         let mut scc_representatives = IndexVec::from_elem_n(next_region_vid, num_sccs);
277
278         for region_vid in definitions.indices() {
279             let scc = constraints_scc.scc(region_vid);
280             let prev_min = scc_representatives[scc];
281             scc_representatives[scc] = region_vid.min(prev_min);
282         }
283
284         scc_representatives
285     }
286
287     /// Initializes the region variables for each universally
288     /// quantified region (lifetime parameter). The first N variables
289     /// always correspond to the regions appearing in the function
290     /// signature (both named and anonymous) and where-clauses. This
291     /// function iterates over those regions and initializes them with
292     /// minimum values.
293     ///
294     /// For example:
295     ///
296     ///     fn foo<'a, 'b>(..) where 'a: 'b
297     ///
298     /// would initialize two variables like so:
299     ///
300     ///     R0 = { CFG, R0 } // 'a
301     ///     R1 = { CFG, R0, R1 } // 'b
302     ///
303     /// Here, R0 represents `'a`, and it contains (a) the entire CFG
304     /// and (b) any universally quantified regions that it outlives,
305     /// which in this case is just itself. R1 (`'b`) in contrast also
306     /// outlives `'a` and hence contains R0 and R1.
307     fn init_free_and_bound_regions(&mut self) {
308         // Update the names (if any)
309         for (external_name, variable) in self.universal_regions.named_universal_regions() {
310             debug!(
311                 "init_universal_regions: region {:?} has external name {:?}",
312                 variable, external_name
313             );
314             self.definitions[variable].external_name = Some(external_name);
315         }
316
317         for variable in self.definitions.indices() {
318             let scc = self.constraint_sccs.scc(variable);
319
320             match self.definitions[variable].origin {
321                 NLLRegionVariableOrigin::FreeRegion => {
322                     // For each free, universally quantified region X:
323
324                     // Add all nodes in the CFG to liveness constraints
325                     self.liveness_constraints.add_all_points(variable);
326                     self.scc_values.add_all_points(scc);
327
328                     // Add `end(X)` into the set for X.
329                     self.scc_values.add_element(scc, variable);
330                 }
331
332                 NLLRegionVariableOrigin::Placeholder(placeholder) => {
333                     // Each placeholder region is only visible from
334                     // its universe `ui` and its extensions. So we
335                     // can't just add it into `scc` unless the
336                     // universe of the scc can name this region.
337                     let scc_universe = self.scc_universes[scc];
338                     if scc_universe.can_name(placeholder.universe) {
339                         self.scc_values.add_element(scc, placeholder);
340                     } else {
341                         debug!(
342                             "init_free_and_bound_regions: placeholder {:?} is \
343                              not compatible with universe {:?} of its SCC {:?}",
344                             placeholder,
345                             scc_universe,
346                             scc,
347                         );
348                         self.add_incompatible_universe(scc);
349                     }
350                 }
351
352                 NLLRegionVariableOrigin::Existential => {
353                     // For existential, regions, nothing to do.
354                 }
355             }
356         }
357     }
358
359     /// Returns an iterator over all the region indices.
360     pub fn regions(&self) -> impl Iterator<Item = RegionVid> {
361         self.definitions.indices()
362     }
363
364     /// Given a universal region in scope on the MIR, returns the
365     /// corresponding index.
366     ///
367     /// (Panics if `r` is not a registered universal region.)
368     pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
369         self.universal_regions.to_region_vid(r)
370     }
371
372     /// Adds annotations for `#[rustc_regions]`; see `UniversalRegions::annotate`.
373     crate fn annotate(&self, tcx: TyCtxt<'_, '_, 'tcx>, err: &mut DiagnosticBuilder<'_>) {
374         self.universal_regions.annotate(tcx, err)
375     }
376
377     /// Returns `true` if the region `r` contains the point `p`.
378     ///
379     /// Panics if called before `solve()` executes,
380     crate fn region_contains(&self, r: impl ToRegionVid, p: impl ToElementIndex) -> bool {
381         let scc = self.constraint_sccs.scc(r.to_region_vid());
382         self.scc_values.contains(scc, p)
383     }
384
385     /// Returns access to the value of `r` for debugging purposes.
386     crate fn region_value_str(&self, r: RegionVid) -> String {
387         let scc = self.constraint_sccs.scc(r.to_region_vid());
388         self.scc_values.region_value_str(scc)
389     }
390
391     /// Returns access to the value of `r` for debugging purposes.
392     crate fn region_universe(&self, r: RegionVid) -> ty::UniverseIndex {
393         let scc = self.constraint_sccs.scc(r.to_region_vid());
394         self.scc_universes[scc]
395     }
396
397     /// Performs region inference and report errors if we see any
398     /// unsatisfiable constraints. If this is a closure, returns the
399     /// region requirements to propagate to our creator, if any.
400     pub(super) fn solve<'gcx>(
401         &mut self,
402         infcx: &InferCtxt<'_, 'gcx, 'tcx>,
403         mir: &Body<'tcx>,
404         upvars: &[Upvar],
405         mir_def_id: DefId,
406         errors_buffer: &mut Vec<Diagnostic>,
407     ) -> Option<ClosureRegionRequirements<'gcx>> {
408         common::time_ext(
409             infcx.tcx.sess.time_extended(),
410             Some(infcx.tcx.sess),
411             &format!("solve_nll_region_constraints({:?})", mir_def_id),
412             || self.solve_inner(infcx, mir, upvars, mir_def_id, errors_buffer),
413         )
414     }
415
416     fn solve_inner<'gcx>(
417         &mut self,
418         infcx: &InferCtxt<'_, 'gcx, 'tcx>,
419         mir: &Body<'tcx>,
420         upvars: &[Upvar],
421         mir_def_id: DefId,
422         errors_buffer: &mut Vec<Diagnostic>,
423     ) -> Option<ClosureRegionRequirements<'gcx>> {
424         self.propagate_constraints(mir);
425
426         // If this is a closure, we can propagate unsatisfied
427         // `outlives_requirements` to our creator, so create a vector
428         // to store those. Otherwise, we'll pass in `None` to the
429         // functions below, which will trigger them to report errors
430         // eagerly.
431         let mut outlives_requirements = if infcx.tcx.is_closure(mir_def_id) {
432             Some(vec![])
433         } else {
434             None
435         };
436
437         self.check_type_tests(
438             infcx,
439             mir,
440             mir_def_id,
441             outlives_requirements.as_mut(),
442             errors_buffer,
443         );
444
445         self.check_universal_regions(
446             infcx,
447             mir,
448             upvars,
449             mir_def_id,
450             outlives_requirements.as_mut(),
451             errors_buffer,
452         );
453
454         let outlives_requirements = outlives_requirements.unwrap_or(vec![]);
455
456         if outlives_requirements.is_empty() {
457             None
458         } else {
459             let num_external_vids = self.universal_regions.num_global_and_external_regions();
460             Some(ClosureRegionRequirements {
461                 num_external_vids,
462                 outlives_requirements,
463             })
464         }
465     }
466
467     /// Propagate the region constraints: this will grow the values
468     /// for each region variable until all the constraints are
469     /// satisfied. Note that some values may grow **too** large to be
470     /// feasible, but we check this later.
471     fn propagate_constraints(&mut self, _mir: &Body<'tcx>) {
472         debug!("propagate_constraints()");
473
474         debug!("propagate_constraints: constraints={:#?}", {
475             let mut constraints: Vec<_> = self.constraints.iter().collect();
476             constraints.sort();
477             constraints
478                 .into_iter()
479                 .map(|c| (c, self.constraint_sccs.scc(c.sup), self.constraint_sccs.scc(c.sub)))
480                 .collect::<Vec<_>>()
481         });
482
483         // To propagate constraints, we walk the DAG induced by the
484         // SCC. For each SCC, we visit its successors and compute
485         // their values, then we union all those values to get our
486         // own.
487         let visited = &mut BitSet::new_empty(self.constraint_sccs.num_sccs());
488         for scc_index in self.constraint_sccs.all_sccs() {
489             self.propagate_constraint_sccs_if_new(scc_index, visited);
490         }
491     }
492
493     #[inline]
494     fn propagate_constraint_sccs_if_new(
495         &mut self,
496         scc_a: ConstraintSccIndex,
497         visited: &mut BitSet<ConstraintSccIndex>,
498     ) {
499         if visited.insert(scc_a) {
500             self.propagate_constraint_sccs_new(scc_a, visited);
501         }
502     }
503
504     fn propagate_constraint_sccs_new(
505         &mut self,
506         scc_a: ConstraintSccIndex,
507         visited: &mut BitSet<ConstraintSccIndex>,
508     ) {
509         let constraint_sccs = self.constraint_sccs.clone();
510
511         // Walk each SCC `B` such that `A: B`...
512         for &scc_b in constraint_sccs.successors(scc_a) {
513             debug!(
514                 "propagate_constraint_sccs: scc_a = {:?} scc_b = {:?}",
515                 scc_a, scc_b
516             );
517
518             // ...compute the value of `B`...
519             self.propagate_constraint_sccs_if_new(scc_b, visited);
520
521             // ...and add elements from `B` into `A`. One complication
522             // arises because of universes: If `B` contains something
523             // that `A` cannot name, then `A` can only contain `B` if
524             // it outlives static.
525             if self.universe_compatible(scc_b, scc_a) {
526                 // `A` can name everything that is in `B`, so just
527                 // merge the bits.
528                 self.scc_values.add_region(scc_a, scc_b);
529             } else {
530                 self.add_incompatible_universe(scc_a);
531             }
532         }
533
534         debug!(
535             "propagate_constraint_sccs: scc_a = {:?} has value {:?}",
536             scc_a,
537             self.scc_values.region_value_str(scc_a),
538         );
539     }
540
541     /// Returns `true` if all the elements in the value of `scc_b` are nameable
542     /// in `scc_a`. Used during constraint propagation, and only once
543     /// the value of `scc_b` has been computed.
544     fn universe_compatible(&self, scc_b: ConstraintSccIndex, scc_a: ConstraintSccIndex) -> bool {
545         let universe_a = self.scc_universes[scc_a];
546
547         // Quick check: if scc_b's declared universe is a subset of
548         // scc_a's declared univese (typically, both are ROOT), then
549         // it cannot contain any problematic universe elements.
550         if universe_a.can_name(self.scc_universes[scc_b]) {
551             return true;
552         }
553
554         // Otherwise, we have to iterate over the universe elements in
555         // B's value, and check whether all of them are nameable
556         // from universe_a
557         self.scc_values
558             .placeholders_contained_in(scc_b)
559             .all(|p| universe_a.can_name(p.universe))
560     }
561
562     /// Extend `scc` so that it can outlive some placeholder region
563     /// from a universe it can't name; at present, the only way for
564     /// this to be true is if `scc` outlives `'static`. This is
565     /// actually stricter than necessary: ideally, we'd support bounds
566     /// like `for<'a: 'b`>` that might then allow us to approximate
567     /// `'a` with `'b` and not `'static`. But it will have to do for
568     /// now.
569     fn add_incompatible_universe(&mut self, scc: ConstraintSccIndex) {
570         debug!("add_incompatible_universe(scc={:?})", scc);
571
572         let fr_static = self.universal_regions.fr_static;
573         self.scc_values.add_all_points(scc);
574         self.scc_values.add_element(scc, fr_static);
575     }
576
577     /// Once regions have been propagated, this method is used to see
578     /// whether the "type tests" produced by typeck were satisfied;
579     /// type tests encode type-outlives relationships like `T:
580     /// 'a`. See `TypeTest` for more details.
581     fn check_type_tests<'gcx>(
582         &self,
583         infcx: &InferCtxt<'_, 'gcx, 'tcx>,
584         mir: &Body<'tcx>,
585         mir_def_id: DefId,
586         mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'gcx>>>,
587         errors_buffer: &mut Vec<Diagnostic>,
588     ) {
589         let tcx = infcx.tcx;
590
591         // Sometimes we register equivalent type-tests that would
592         // result in basically the exact same error being reported to
593         // the user. Avoid that.
594         let mut deduplicate_errors = FxHashSet::default();
595
596         for type_test in &self.type_tests {
597             debug!("check_type_test: {:?}", type_test);
598
599             let generic_ty = type_test.generic_kind.to_ty(tcx);
600             if self.eval_verify_bound(
601                 tcx,
602                 mir,
603                 generic_ty,
604                 type_test.lower_bound,
605                 &type_test.verify_bound,
606             ) {
607                 continue;
608             }
609
610             if let Some(propagated_outlives_requirements) = &mut propagated_outlives_requirements {
611                 if self.try_promote_type_test(
612                     infcx,
613                     mir,
614                     type_test,
615                     propagated_outlives_requirements,
616                 ) {
617                     continue;
618                 }
619             }
620
621             // Type-test failed. Report the error.
622
623             // Try to convert the lower-bound region into something named we can print for the user.
624             let lower_bound_region = self.to_error_region(type_test.lower_bound);
625
626             // Skip duplicate-ish errors.
627             let type_test_span = type_test.locations.span(mir);
628             let erased_generic_kind = tcx.erase_regions(&type_test.generic_kind);
629             if !deduplicate_errors.insert((
630                 erased_generic_kind,
631                 lower_bound_region,
632                 type_test.locations,
633             )) {
634                 continue;
635             } else {
636                 debug!(
637                     "check_type_test: reporting error for erased_generic_kind={:?}, \
638                      lower_bound_region={:?}, \
639                      type_test.locations={:?}",
640                     erased_generic_kind, lower_bound_region, type_test.locations,
641                 );
642             }
643
644             if let Some(lower_bound_region) = lower_bound_region {
645                 let region_scope_tree = &tcx.region_scope_tree(mir_def_id);
646                 infcx
647                     .construct_generic_bound_failure(
648                         region_scope_tree,
649                         type_test_span,
650                         None,
651                         type_test.generic_kind,
652                         lower_bound_region,
653                     )
654                     .buffer(errors_buffer);
655             } else {
656                 // FIXME. We should handle this case better. It
657                 // indicates that we have e.g., some region variable
658                 // whose value is like `'a+'b` where `'a` and `'b` are
659                 // distinct unrelated univesal regions that are not
660                 // known to outlive one another. It'd be nice to have
661                 // some examples where this arises to decide how best
662                 // to report it; we could probably handle it by
663                 // iterating over the universal regions and reporting
664                 // an error that multiple bounds are required.
665                 tcx.sess
666                     .struct_span_err(
667                         type_test_span,
668                         &format!("`{}` does not live long enough", type_test.generic_kind,),
669                     )
670                     .buffer(errors_buffer);
671             }
672         }
673     }
674
675     /// Converts a region inference variable into a `ty::Region` that
676     /// we can use for error reporting. If `r` is universally bound,
677     /// then we use the name that we have on record for it. If `r` is
678     /// existentially bound, then we check its inferred value and try
679     /// to find a good name from that. Returns `None` if we can't find
680     /// one (e.g., this is just some random part of the CFG).
681     pub fn to_error_region(&self, r: RegionVid) -> Option<ty::Region<'tcx>> {
682         self.to_error_region_vid(r).and_then(|r| self.definitions[r].external_name)
683     }
684
685     /// Returns the [RegionVid] corresponding to the region returned by
686     /// `to_error_region`.
687     pub fn to_error_region_vid(&self, r: RegionVid) -> Option<RegionVid> {
688         if self.universal_regions.is_universal_region(r) {
689             Some(r)
690         } else {
691             let r_scc = self.constraint_sccs.scc(r);
692             let upper_bound = self.universal_upper_bound(r);
693             if self.scc_values.contains(r_scc, upper_bound) {
694                 self.to_error_region_vid(upper_bound)
695             } else {
696                 None
697             }
698         }
699     }
700
701     /// Invoked when we have some type-test (e.g., `T: 'X`) that we cannot
702     /// prove to be satisfied. If this is a closure, we will attempt to
703     /// "promote" this type-test into our `ClosureRegionRequirements` and
704     /// hence pass it up the creator. To do this, we have to phrase the
705     /// type-test in terms of external free regions, as local free
706     /// regions are not nameable by the closure's creator.
707     ///
708     /// Promotion works as follows: we first check that the type `T`
709     /// contains only regions that the creator knows about. If this is
710     /// true, then -- as a consequence -- we know that all regions in
711     /// the type `T` are free regions that outlive the closure body. If
712     /// false, then promotion fails.
713     ///
714     /// Once we've promoted T, we have to "promote" `'X` to some region
715     /// that is "external" to the closure. Generally speaking, a region
716     /// may be the union of some points in the closure body as well as
717     /// various free lifetimes. We can ignore the points in the closure
718     /// body: if the type T can be expressed in terms of external regions,
719     /// we know it outlives the points in the closure body. That
720     /// just leaves the free regions.
721     ///
722     /// The idea then is to lower the `T: 'X` constraint into multiple
723     /// bounds -- e.g., if `'X` is the union of two free lifetimes,
724     /// `'1` and `'2`, then we would create `T: '1` and `T: '2`.
725     fn try_promote_type_test<'gcx>(
726         &self,
727         infcx: &InferCtxt<'_, 'gcx, 'tcx>,
728         mir: &Body<'tcx>,
729         type_test: &TypeTest<'tcx>,
730         propagated_outlives_requirements: &mut Vec<ClosureOutlivesRequirement<'gcx>>,
731     ) -> bool {
732         let tcx = infcx.tcx;
733
734         let TypeTest {
735             generic_kind,
736             lower_bound,
737             locations,
738             verify_bound: _,
739         } = type_test;
740
741         let generic_ty = generic_kind.to_ty(tcx);
742         let subject = match self.try_promote_type_test_subject(infcx, generic_ty) {
743             Some(s) => s,
744             None => return false,
745         };
746
747         // For each region outlived by lower_bound find a non-local,
748         // universal region (it may be the same region) and add it to
749         // `ClosureOutlivesRequirement`.
750         let r_scc = self.constraint_sccs.scc(*lower_bound);
751         for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
752             // Check whether we can already prove that the "subject" outlives `ur`.
753             // If so, we don't have to propagate this requirement to our caller.
754             //
755             // To continue the example from the function, if we are trying to promote
756             // a requirement that `T: 'X`, and we know that `'X = '1 + '2` (i.e., the union
757             // `'1` and `'2`), then in this loop `ur` will be `'1` (and `'2`). So here
758             // we check whether `T: '1` is something we *can* prove. If so, no need
759             // to propagate that requirement.
760             //
761             // This is needed because -- particularly in the case
762             // where `ur` is a local bound -- we are sometimes in a
763             // position to prove things that our caller cannot.  See
764             // #53570 for an example.
765             if self.eval_verify_bound(tcx, mir, generic_ty, ur, &type_test.verify_bound) {
766                 continue;
767             }
768
769             debug!("try_promote_type_test: ur={:?}", ur);
770
771             let non_local_ub = self.universal_region_relations.non_local_upper_bounds(&ur);
772             debug!("try_promote_type_test: non_local_ub={:?}", non_local_ub);
773
774             // This is slightly too conservative. To show T: '1, given `'2: '1`
775             // and `'3: '1` we only need to prove that T: '2 *or* T: '3, but to
776             // avoid potential non-determinism we approximate this by requiring
777             // T: '1 and T: '2.
778             for &upper_bound in non_local_ub {
779                 debug_assert!(self.universal_regions.is_universal_region(upper_bound));
780                 debug_assert!(!self.universal_regions.is_local_free_region(upper_bound));
781
782                 let requirement = ClosureOutlivesRequirement {
783                     subject,
784                     outlived_free_region: upper_bound,
785                     blame_span: locations.span(mir),
786                     category: ConstraintCategory::Boring,
787                 };
788                 debug!("try_promote_type_test: pushing {:#?}", requirement);
789                 propagated_outlives_requirements.push(requirement);
790             }
791         }
792         true
793     }
794
795     /// When we promote a type test `T: 'r`, we have to convert the
796     /// type `T` into something we can store in a query result (so
797     /// something allocated for `'gcx`). This is problematic if `ty`
798     /// contains regions. During the course of NLL region checking, we
799     /// will have replaced all of those regions with fresh inference
800     /// variables. To create a test subject, we want to replace those
801     /// inference variables with some region from the closure
802     /// signature -- this is not always possible, so this is a
803     /// fallible process. Presuming we do find a suitable region, we
804     /// will represent it with a `ReClosureBound`, which is a
805     /// `RegionKind` variant that can be allocated in the gcx.
806     fn try_promote_type_test_subject<'gcx>(
807         &self,
808         infcx: &InferCtxt<'_, 'gcx, 'tcx>,
809         ty: Ty<'tcx>,
810     ) -> Option<ClosureOutlivesSubject<'gcx>> {
811         let tcx = infcx.tcx;
812         let gcx = tcx.global_tcx();
813
814         debug!("try_promote_type_test_subject(ty = {:?})", ty);
815
816         let ty = tcx.fold_regions(&ty, &mut false, |r, _depth| {
817             let region_vid = self.to_region_vid(r);
818
819             // The challenge if this. We have some region variable `r`
820             // whose value is a set of CFG points and universal
821             // regions. We want to find if that set is *equivalent* to
822             // any of the named regions found in the closure.
823             //
824             // To do so, we compute the
825             // `non_local_universal_upper_bound`. This will be a
826             // non-local, universal region that is greater than `r`.
827             // However, it might not be *contained* within `r`, so
828             // then we further check whether this bound is contained
829             // in `r`. If so, we can say that `r` is equivalent to the
830             // bound.
831             //
832             // Let's work through a few examples. For these, imagine
833             // that we have 3 non-local regions (I'll denote them as
834             // `'static`, `'a`, and `'b`, though of course in the code
835             // they would be represented with indices) where:
836             //
837             // - `'static: 'a`
838             // - `'static: 'b`
839             //
840             // First, let's assume that `r` is some existential
841             // variable with an inferred value `{'a, 'static}` (plus
842             // some CFG nodes). In this case, the non-local upper
843             // bound is `'static`, since that outlives `'a`. `'static`
844             // is also a member of `r` and hence we consider `r`
845             // equivalent to `'static` (and replace it with
846             // `'static`).
847             //
848             // Now let's consider the inferred value `{'a, 'b}`. This
849             // means `r` is effectively `'a | 'b`. I'm not sure if
850             // this can come about, actually, but assuming it did, we
851             // would get a non-local upper bound of `'static`. Since
852             // `'static` is not contained in `r`, we would fail to
853             // find an equivalent.
854             let upper_bound = self.non_local_universal_upper_bound(region_vid);
855             if self.region_contains(region_vid, upper_bound) {
856                 tcx.mk_region(ty::ReClosureBound(upper_bound))
857             } else {
858                 // In the case of a failure, use a `ReVar`
859                 // result. This will cause the `lift` later on to
860                 // fail.
861                 r
862             }
863         });
864         debug!("try_promote_type_test_subject: folded ty = {:?}", ty);
865
866         // `lift` will only fail if we failed to promote some region.
867         let ty = gcx.lift(&ty)?;
868
869         Some(ClosureOutlivesSubject::Ty(ty))
870     }
871
872     /// Given some universal or existential region `r`, finds a
873     /// non-local, universal region `r+` that outlives `r` at entry to (and
874     /// exit from) the closure. In the worst case, this will be
875     /// `'static`.
876     ///
877     /// This is used for two purposes. First, if we are propagated
878     /// some requirement `T: r`, we can use this method to enlarge `r`
879     /// to something we can encode for our creator (which only knows
880     /// about non-local, universal regions). It is also used when
881     /// encoding `T` as part of `try_promote_type_test_subject` (see
882     /// that fn for details).
883     ///
884     /// This is based on the result `'y` of `universal_upper_bound`,
885     /// except that it converts further takes the non-local upper
886     /// bound of `'y`, so that the final result is non-local.
887     fn non_local_universal_upper_bound(&self, r: RegionVid) -> RegionVid {
888         debug!(
889             "non_local_universal_upper_bound(r={:?}={})",
890             r,
891             self.region_value_str(r)
892         );
893
894         let lub = self.universal_upper_bound(r);
895
896         // Grow further to get smallest universal region known to
897         // creator.
898         let non_local_lub = self.universal_region_relations.non_local_upper_bound(lub);
899
900         debug!(
901             "non_local_universal_upper_bound: non_local_lub={:?}",
902             non_local_lub
903         );
904
905         non_local_lub
906     }
907
908     /// Returns a universally quantified region that outlives the
909     /// value of `r` (`r` may be existentially or universally
910     /// quantified).
911     ///
912     /// Since `r` is (potentially) an existential region, it has some
913     /// value which may include (a) any number of points in the CFG
914     /// and (b) any number of `end('x)` elements of universally
915     /// quantified regions. To convert this into a single universal
916     /// region we do as follows:
917     ///
918     /// - Ignore the CFG points in `'r`. All universally quantified regions
919     ///   include the CFG anyhow.
920     /// - For each `end('x)` element in `'r`, compute the mutual LUB, yielding
921     ///   a result `'y`.
922     fn universal_upper_bound(&self, r: RegionVid) -> RegionVid {
923         debug!(
924             "universal_upper_bound(r={:?}={})",
925             r,
926             self.region_value_str(r)
927         );
928
929         // Find the smallest universal region that contains all other
930         // universal regions within `region`.
931         let mut lub = self.universal_regions.fr_fn_body;
932         let r_scc = self.constraint_sccs.scc(r);
933         for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
934             lub = self.universal_region_relations.postdom_upper_bound(lub, ur);
935         }
936
937         debug!("universal_upper_bound: r={:?} lub={:?}", r, lub);
938
939         lub
940     }
941
942     /// Tests if `test` is true when applied to `lower_bound` at
943     /// `point`.
944     fn eval_verify_bound(
945         &self,
946         tcx: TyCtxt<'_, '_, 'tcx>,
947         mir: &Body<'tcx>,
948         generic_ty: Ty<'tcx>,
949         lower_bound: RegionVid,
950         verify_bound: &VerifyBound<'tcx>,
951     ) -> bool {
952         debug!(
953             "eval_verify_bound(lower_bound={:?}, verify_bound={:?})",
954             lower_bound, verify_bound
955         );
956
957         match verify_bound {
958             VerifyBound::IfEq(test_ty, verify_bound1) => {
959                 self.eval_if_eq(tcx, mir, generic_ty, lower_bound, test_ty, verify_bound1)
960             }
961
962             VerifyBound::OutlivedBy(r) => {
963                 let r_vid = self.to_region_vid(r);
964                 self.eval_outlives(mir, r_vid, lower_bound)
965             }
966
967             VerifyBound::AnyBound(verify_bounds) => verify_bounds.iter().any(|verify_bound| {
968                 self.eval_verify_bound(tcx, mir, generic_ty, lower_bound, verify_bound)
969             }),
970
971             VerifyBound::AllBounds(verify_bounds) => verify_bounds.iter().all(|verify_bound| {
972                 self.eval_verify_bound(tcx, mir, generic_ty, lower_bound, verify_bound)
973             }),
974         }
975     }
976
977     fn eval_if_eq(
978         &self,
979         tcx: TyCtxt<'_, '_, 'tcx>,
980         mir: &Body<'tcx>,
981         generic_ty: Ty<'tcx>,
982         lower_bound: RegionVid,
983         test_ty: Ty<'tcx>,
984         verify_bound: &VerifyBound<'tcx>,
985     ) -> bool {
986         let generic_ty_normalized = self.normalize_to_scc_representatives(tcx, generic_ty);
987         let test_ty_normalized = self.normalize_to_scc_representatives(tcx, test_ty);
988         if generic_ty_normalized == test_ty_normalized {
989             self.eval_verify_bound(tcx, mir, generic_ty, lower_bound, verify_bound)
990         } else {
991             false
992         }
993     }
994
995     /// This is a conservative normalization procedure. It takes every
996     /// free region in `value` and replaces it with the
997     /// "representative" of its SCC (see `scc_representatives` field).
998     /// We are guaranteed that if two values normalize to the same
999     /// thing, then they are equal; this is a conservative check in
1000     /// that they could still be equal even if they normalize to
1001     /// different results. (For example, there might be two regions
1002     /// with the same value that are not in the same SCC).
1003     ///
1004     /// N.B., this is not an ideal approach and I would like to revisit
1005     /// it. However, it works pretty well in practice. In particular,
1006     /// this is needed to deal with projection outlives bounds like
1007     ///
1008     ///     <T as Foo<'0>>::Item: '1
1009     ///
1010     /// In particular, this routine winds up being important when
1011     /// there are bounds like `where <T as Foo<'a>>::Item: 'b` in the
1012     /// environment. In this case, if we can show that `'0 == 'a`,
1013     /// and that `'b: '1`, then we know that the clause is
1014     /// satisfied. In such cases, particularly due to limitations of
1015     /// the trait solver =), we usually wind up with a where-clause like
1016     /// `T: Foo<'a>` in scope, which thus forces `'0 == 'a` to be added as
1017     /// a constraint, and thus ensures that they are in the same SCC.
1018     ///
1019     /// So why can't we do a more correct routine? Well, we could
1020     /// *almost* use the `relate_tys` code, but the way it is
1021     /// currently setup it creates inference variables to deal with
1022     /// higher-ranked things and so forth, and right now the inference
1023     /// context is not permitted to make more inference variables. So
1024     /// we use this kind of hacky solution.
1025     fn normalize_to_scc_representatives<T>(&self, tcx: TyCtxt<'_, '_, 'tcx>, value: T) -> T
1026     where
1027         T: TypeFoldable<'tcx>,
1028     {
1029         tcx.fold_regions(&value, &mut false, |r, _db| {
1030             let vid = self.to_region_vid(r);
1031             let scc = self.constraint_sccs.scc(vid);
1032             let repr = self.scc_representatives[scc];
1033             tcx.mk_region(ty::ReVar(repr))
1034         })
1035     }
1036
1037     // Evaluate whether `sup_region: sub_region @ point`.
1038     fn eval_outlives(
1039         &self,
1040         _mir: &Body<'tcx>,
1041         sup_region: RegionVid,
1042         sub_region: RegionVid,
1043     ) -> bool {
1044         debug!("eval_outlives({:?}: {:?})", sup_region, sub_region);
1045
1046         debug!(
1047             "eval_outlives: sup_region's value = {:?}",
1048             self.region_value_str(sup_region),
1049         );
1050         debug!(
1051             "eval_outlives: sub_region's value = {:?}",
1052             self.region_value_str(sub_region),
1053         );
1054
1055         let sub_region_scc = self.constraint_sccs.scc(sub_region);
1056         let sup_region_scc = self.constraint_sccs.scc(sup_region);
1057
1058         // Both the `sub_region` and `sup_region` consist of the union
1059         // of some number of universal regions (along with the union
1060         // of various points in the CFG; ignore those points for
1061         // now). Therefore, the sup-region outlives the sub-region if,
1062         // for each universal region R1 in the sub-region, there
1063         // exists some region R2 in the sup-region that outlives R1.
1064         let universal_outlives = self.scc_values
1065             .universal_regions_outlived_by(sub_region_scc)
1066             .all(|r1| {
1067                 self.scc_values
1068                     .universal_regions_outlived_by(sup_region_scc)
1069                     .any(|r2| self.universal_region_relations.outlives(r2, r1))
1070             });
1071
1072         if !universal_outlives {
1073             return false;
1074         }
1075
1076         // Now we have to compare all the points in the sub region and make
1077         // sure they exist in the sup region.
1078
1079         if self.universal_regions.is_universal_region(sup_region) {
1080             // Micro-opt: universal regions contain all points.
1081             return true;
1082         }
1083
1084         self.scc_values
1085             .contains_points(sup_region_scc, sub_region_scc)
1086     }
1087
1088     /// Once regions have been propagated, this method is used to see
1089     /// whether any of the constraints were too strong. In particular,
1090     /// we want to check for a case where a universally quantified
1091     /// region exceeded its bounds. Consider:
1092     ///
1093     ///     fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1094     ///
1095     /// In this case, returning `x` requires `&'a u32 <: &'b u32`
1096     /// and hence we establish (transitively) a constraint that
1097     /// `'a: 'b`. The `propagate_constraints` code above will
1098     /// therefore add `end('a)` into the region for `'b` -- but we
1099     /// have no evidence that `'b` outlives `'a`, so we want to report
1100     /// an error.
1101     ///
1102     /// If `propagated_outlives_requirements` is `Some`, then we will
1103     /// push unsatisfied obligations into there. Otherwise, we'll
1104     /// report them as errors.
1105     fn check_universal_regions<'gcx>(
1106         &self,
1107         infcx: &InferCtxt<'_, 'gcx, 'tcx>,
1108         mir: &Body<'tcx>,
1109         upvars: &[Upvar],
1110         mir_def_id: DefId,
1111         mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'gcx>>>,
1112         errors_buffer: &mut Vec<Diagnostic>,
1113     ) {
1114         for (fr, fr_definition) in self.definitions.iter_enumerated() {
1115             match fr_definition.origin {
1116                 NLLRegionVariableOrigin::FreeRegion => {
1117                     // Go through each of the universal regions `fr` and check that
1118                     // they did not grow too large, accumulating any requirements
1119                     // for our caller into the `outlives_requirements` vector.
1120                     self.check_universal_region(
1121                         infcx,
1122                         mir,
1123                         upvars,
1124                         mir_def_id,
1125                         fr,
1126                         &mut propagated_outlives_requirements,
1127                         errors_buffer,
1128                     );
1129                 }
1130
1131                 NLLRegionVariableOrigin::Placeholder(placeholder) => {
1132                     self.check_bound_universal_region(infcx, mir, mir_def_id, fr, placeholder);
1133                 }
1134
1135                 NLLRegionVariableOrigin::Existential => {
1136                     // nothing to check here
1137                 }
1138             }
1139         }
1140     }
1141
1142     /// Checks the final value for the free region `fr` to see if it
1143     /// grew too large. In particular, examine what `end(X)` points
1144     /// wound up in `fr`'s final value; for each `end(X)` where `X !=
1145     /// fr`, we want to check that `fr: X`. If not, that's either an
1146     /// error, or something we have to propagate to our creator.
1147     ///
1148     /// Things that are to be propagated are accumulated into the
1149     /// `outlives_requirements` vector.
1150     fn check_universal_region<'gcx>(
1151         &self,
1152         infcx: &InferCtxt<'_, 'gcx, 'tcx>,
1153         mir: &Body<'tcx>,
1154         upvars: &[Upvar],
1155         mir_def_id: DefId,
1156         longer_fr: RegionVid,
1157         propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'gcx>>>,
1158         errors_buffer: &mut Vec<Diagnostic>,
1159     ) {
1160         debug!("check_universal_region(fr={:?})", longer_fr);
1161
1162         let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1163
1164         // Because this free region must be in the ROOT universe, we
1165         // know it cannot contain any bound universes.
1166         assert!(self.scc_universes[longer_fr_scc] == ty::UniverseIndex::ROOT);
1167         debug_assert!(
1168             self.scc_values
1169                 .placeholders_contained_in(longer_fr_scc)
1170                 .next()
1171                 .is_none()
1172         );
1173
1174         // Only check all of the relations for the main representative of each
1175         // SCC, otherwise just check that we outlive said representative. This
1176         // reduces the number of redundant relations propagated out of
1177         // closures.
1178         // Note that the representative will be a universal region if there is
1179         // one in this SCC, so we will always check the representative here.
1180         let representative = self.scc_representatives[longer_fr_scc];
1181         if representative != longer_fr {
1182             self.check_universal_region_relation(
1183                 longer_fr,
1184                 representative,
1185                 infcx,
1186                 mir,
1187                 upvars,
1188                 mir_def_id,
1189                 propagated_outlives_requirements,
1190                 errors_buffer,
1191             );
1192             return;
1193         }
1194
1195         // Find every region `o` such that `fr: o`
1196         // (because `fr` includes `end(o)`).
1197         for shorter_fr in self.scc_values.universal_regions_outlived_by(longer_fr_scc) {
1198             if let Some(ErrorReported) = self.check_universal_region_relation(
1199                 longer_fr,
1200                 shorter_fr,
1201                 infcx,
1202                 mir,
1203                 upvars,
1204                 mir_def_id,
1205                 propagated_outlives_requirements,
1206                 errors_buffer,
1207             ) {
1208                 // continuing to iterate just reports more errors than necessary
1209                 return;
1210             }
1211         }
1212     }
1213
1214     fn check_universal_region_relation(
1215         &self,
1216         longer_fr: RegionVid,
1217         shorter_fr: RegionVid,
1218         infcx: &InferCtxt<'_, 'gcx, 'tcx>,
1219         mir: &Body<'tcx>,
1220         upvars: &[Upvar],
1221         mir_def_id: DefId,
1222         propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'gcx>>>,
1223         errors_buffer: &mut Vec<Diagnostic>,
1224     ) -> Option<ErrorReported> {
1225         // If it is known that `fr: o`, carry on.
1226         if self.universal_region_relations
1227             .outlives(longer_fr, shorter_fr)
1228         {
1229             return None;
1230         }
1231
1232         debug!(
1233             "check_universal_region_relation: fr={:?} does not outlive shorter_fr={:?}",
1234             longer_fr, shorter_fr,
1235         );
1236
1237         if let Some(propagated_outlives_requirements) = propagated_outlives_requirements {
1238             // Shrink `longer_fr` until we find a non-local region (if we do).
1239             // We'll call it `fr-` -- it's ever so slightly smaller than
1240             // `longer_fr`.
1241
1242             if let Some(fr_minus) = self
1243                 .universal_region_relations
1244                 .non_local_lower_bound(longer_fr)
1245             {
1246                 debug!("check_universal_region: fr_minus={:?}", fr_minus);
1247
1248                 let blame_span_category = self.find_outlives_blame_span(mir, longer_fr, shorter_fr);
1249
1250                 // Grow `shorter_fr` until we find some non-local regions. (We
1251                 // always will.)  We'll call them `shorter_fr+` -- they're ever
1252                 // so slightly larger than `shorter_fr`.
1253                 let shorter_fr_plus = self.universal_region_relations
1254                     .non_local_upper_bounds(&shorter_fr);
1255                 debug!(
1256                     "check_universal_region: shorter_fr_plus={:?}",
1257                     shorter_fr_plus
1258                 );
1259                 for &&fr in &shorter_fr_plus {
1260                     // Push the constraint `fr-: shorter_fr+`
1261                     propagated_outlives_requirements.push(ClosureOutlivesRequirement {
1262                         subject: ClosureOutlivesSubject::Region(fr_minus),
1263                         outlived_free_region: fr,
1264                         blame_span: blame_span_category.1,
1265                         category: blame_span_category.0,
1266                     });
1267                 }
1268                 return None;
1269             }
1270         }
1271
1272         // If we are not in a context where we can't propagate errors, or we
1273         // could not shrink `fr` to something smaller, then just report an
1274         // error.
1275         //
1276         // Note: in this case, we use the unapproximated regions to report the
1277         // error. This gives better error messages in some cases.
1278         self.report_error(mir, upvars, infcx, mir_def_id, longer_fr, shorter_fr, errors_buffer);
1279         Some(ErrorReported)
1280     }
1281
1282     fn check_bound_universal_region<'gcx>(
1283         &self,
1284         infcx: &InferCtxt<'_, 'gcx, 'tcx>,
1285         mir: &Body<'tcx>,
1286         _mir_def_id: DefId,
1287         longer_fr: RegionVid,
1288         placeholder: ty::PlaceholderRegion,
1289     ) {
1290         debug!(
1291             "check_bound_universal_region(fr={:?}, placeholder={:?})",
1292             longer_fr, placeholder,
1293         );
1294
1295         let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1296         debug!(
1297             "check_bound_universal_region: longer_fr_scc={:?}",
1298             longer_fr_scc,
1299         );
1300
1301         // If we have some bound universal region `'a`, then the only
1302         // elements it can contain is itself -- we don't know anything
1303         // else about it!
1304         let error_element = match {
1305             self.scc_values
1306                 .elements_contained_in(longer_fr_scc)
1307                 .find(|element| match element {
1308                     RegionElement::Location(_) => true,
1309                     RegionElement::RootUniversalRegion(_) => true,
1310                     RegionElement::PlaceholderRegion(placeholder1) => placeholder != *placeholder1,
1311                 })
1312         } {
1313             Some(v) => v,
1314             None => return,
1315         };
1316         debug!("check_bound_universal_region: error_element = {:?}", error_element);
1317
1318         // Find the region that introduced this `error_element`.
1319         let error_region = match error_element {
1320             RegionElement::Location(l) => self.find_sub_region_live_at(longer_fr, l),
1321             RegionElement::RootUniversalRegion(r) => r,
1322             RegionElement::PlaceholderRegion(error_placeholder) => self.definitions
1323                 .iter_enumerated()
1324                 .filter_map(|(r, definition)| match definition.origin {
1325                     NLLRegionVariableOrigin::Placeholder(p) if p == error_placeholder => Some(r),
1326                     _ => None,
1327                 })
1328                 .next()
1329                 .unwrap(),
1330         };
1331
1332         // Find the code to blame for the fact that `longer_fr` outlives `error_fr`.
1333         let (_, span) = self.find_outlives_blame_span(mir, longer_fr, error_region);
1334
1335         // Obviously, this error message is far from satisfactory.
1336         // At present, though, it only appears in unit tests --
1337         // the AST-based checker uses a more conservative check,
1338         // so to even see this error, one must pass in a special
1339         // flag.
1340         let mut diag = infcx
1341             .tcx
1342             .sess
1343             .struct_span_err(span, "higher-ranked subtype error");
1344         diag.emit();
1345     }
1346 }
1347
1348 impl<'tcx> RegionDefinition<'tcx> {
1349     fn new(universe: ty::UniverseIndex, rv_origin: RegionVariableOrigin) -> Self {
1350         // Create a new region definition. Note that, for free
1351         // regions, the `external_name` field gets updated later in
1352         // `init_universal_regions`.
1353
1354         let origin = match rv_origin {
1355             RegionVariableOrigin::NLL(origin) => origin,
1356             _ => NLLRegionVariableOrigin::Existential,
1357         };
1358
1359         Self {
1360             origin,
1361             universe,
1362             external_name: None,
1363         }
1364     }
1365 }
1366
1367 pub trait ClosureRegionRequirementsExt<'gcx, 'tcx> {
1368     fn apply_requirements(
1369         &self,
1370         tcx: TyCtxt<'_, 'gcx, 'tcx>,
1371         closure_def_id: DefId,
1372         closure_substs: SubstsRef<'tcx>,
1373     ) -> Vec<QueryRegionConstraint<'tcx>>;
1374
1375     fn subst_closure_mapping<T>(
1376         &self,
1377         tcx: TyCtxt<'_, 'gcx, 'tcx>,
1378         closure_mapping: &IndexVec<RegionVid, ty::Region<'tcx>>,
1379         value: &T,
1380     ) -> T
1381     where
1382         T: TypeFoldable<'tcx>;
1383 }
1384
1385 impl<'gcx, 'tcx> ClosureRegionRequirementsExt<'gcx, 'tcx> for ClosureRegionRequirements<'gcx> {
1386     /// Given an instance T of the closure type, this method
1387     /// instantiates the "extra" requirements that we computed for the
1388     /// closure into the inference context. This has the effect of
1389     /// adding new outlives obligations to existing variables.
1390     ///
1391     /// As described on `ClosureRegionRequirements`, the extra
1392     /// requirements are expressed in terms of regionvids that index
1393     /// into the free regions that appear on the closure type. So, to
1394     /// do this, we first copy those regions out from the type T into
1395     /// a vector. Then we can just index into that vector to extract
1396     /// out the corresponding region from T and apply the
1397     /// requirements.
1398     fn apply_requirements(
1399         &self,
1400         tcx: TyCtxt<'_, 'gcx, 'tcx>,
1401         closure_def_id: DefId,
1402         closure_substs: SubstsRef<'tcx>,
1403     ) -> Vec<QueryRegionConstraint<'tcx>> {
1404         debug!(
1405             "apply_requirements(closure_def_id={:?}, closure_substs={:?})",
1406             closure_def_id, closure_substs
1407         );
1408
1409         // Extract the values of the free regions in `closure_substs`
1410         // into a vector.  These are the regions that we will be
1411         // relating to one another.
1412         let closure_mapping = &UniversalRegions::closure_mapping(
1413             tcx,
1414             closure_substs,
1415             self.num_external_vids,
1416             tcx.closure_base_def_id(closure_def_id),
1417         );
1418         debug!("apply_requirements: closure_mapping={:?}", closure_mapping);
1419
1420         // Create the predicates.
1421         self.outlives_requirements
1422             .iter()
1423             .map(|outlives_requirement| {
1424                 let outlived_region = closure_mapping[outlives_requirement.outlived_free_region];
1425
1426                 match outlives_requirement.subject {
1427                     ClosureOutlivesSubject::Region(region) => {
1428                         let region = closure_mapping[region];
1429                         debug!(
1430                             "apply_requirements: region={:?} \
1431                              outlived_region={:?} \
1432                              outlives_requirement={:?}",
1433                             region, outlived_region, outlives_requirement,
1434                         );
1435                         ty::Binder::dummy(ty::OutlivesPredicate(region.into(), outlived_region))
1436                     }
1437
1438                     ClosureOutlivesSubject::Ty(ty) => {
1439                         let ty = self.subst_closure_mapping(tcx, closure_mapping, &ty);
1440                         debug!(
1441                             "apply_requirements: ty={:?} \
1442                              outlived_region={:?} \
1443                              outlives_requirement={:?}",
1444                             ty, outlived_region, outlives_requirement,
1445                         );
1446                         ty::Binder::dummy(ty::OutlivesPredicate(ty.into(), outlived_region))
1447                     }
1448                 }
1449             })
1450             .collect()
1451     }
1452
1453     fn subst_closure_mapping<T>(
1454         &self,
1455         tcx: TyCtxt<'_, 'gcx, 'tcx>,
1456         closure_mapping: &IndexVec<RegionVid, ty::Region<'tcx>>,
1457         value: &T,
1458     ) -> T
1459     where
1460         T: TypeFoldable<'tcx>,
1461     {
1462         tcx.fold_regions(value, &mut false, |r, _depth| {
1463             if let ty::ReClosureBound(vid) = r {
1464                 closure_mapping[*vid]
1465             } else {
1466                 bug!(
1467                     "subst_closure_mapping: encountered non-closure bound free region {:?}",
1468                     r
1469                 )
1470             }
1471         })
1472     }
1473 }