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