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