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