]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/region_infer/mod.rs
Rollup merge of #106779 - RReverser:patch-2, r=Mark-Simulacrum
[rust.git] / compiler / rustc_borrowck / src / region_infer / mod.rs
1 use std::collections::VecDeque;
2 use std::rc::Rc;
3
4 use rustc_data_structures::binary_search_util;
5 use rustc_data_structures::frozen::Frozen;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7 use rustc_data_structures::graph::scc::Sccs;
8 use rustc_errors::Diagnostic;
9 use rustc_hir::def_id::CRATE_DEF_ID;
10 use rustc_index::vec::IndexVec;
11 use rustc_infer::infer::outlives::test_type_match;
12 use rustc_infer::infer::region_constraints::{GenericKind, VarInfos, VerifyBound, VerifyIfEq};
13 use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin};
14 use rustc_middle::mir::{
15     Body, ClosureOutlivesRequirement, ClosureOutlivesSubject, ClosureRegionRequirements,
16     ConstraintCategory, Local, Location, ReturnConstraint, TerminatorKind,
17 };
18 use rustc_middle::traits::ObligationCause;
19 use rustc_middle::traits::ObligationCauseCode;
20 use rustc_middle::ty::{self, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitable};
21 use rustc_span::Span;
22
23 use crate::{
24     constraints::{
25         graph::NormalConstraintGraph, ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet,
26     },
27     diagnostics::{RegionErrorKind, RegionErrors, UniverseInfo},
28     member_constraints::{MemberConstraintSet, NllMemberConstraintIndex},
29     nll::{PoloniusOutput, ToRegionVid},
30     region_infer::reverse_sccs::ReverseSccGraph,
31     region_infer::values::{
32         LivenessValues, PlaceholderIndices, RegionElement, RegionValueElements, RegionValues,
33         ToElementIndex,
34     },
35     type_check::{free_region_relations::UniversalRegionRelations, Locations},
36     universal_regions::UniversalRegions,
37 };
38
39 mod dump_mir;
40 mod graphviz;
41 mod opaque_types;
42 mod reverse_sccs;
43
44 pub mod values;
45
46 pub struct RegionInferenceContext<'tcx> {
47     pub var_infos: VarInfos,
48
49     /// Contains the definition for every region variable. Region
50     /// variables are identified by their index (`RegionVid`). The
51     /// definition contains information about where the region came
52     /// from as well as its final inferred value.
53     definitions: IndexVec<RegionVid, RegionDefinition<'tcx>>,
54
55     /// The liveness constraints added to each region. For most
56     /// regions, these start out empty and steadily grow, though for
57     /// each universally quantified region R they start out containing
58     /// the entire CFG and `end(R)`.
59     liveness_constraints: LivenessValues<RegionVid>,
60
61     /// The outlives constraints computed by the type-check.
62     constraints: Frozen<OutlivesConstraintSet<'tcx>>,
63
64     /// The constraint-set, but in graph form, making it easy to traverse
65     /// the constraints adjacent to a particular region. Used to construct
66     /// the SCC (see `constraint_sccs`) and for error reporting.
67     constraint_graph: Frozen<NormalConstraintGraph>,
68
69     /// The SCC computed from `constraints` and the constraint
70     /// graph. We have an edge from SCC A to SCC B if `A: B`. Used to
71     /// compute the values of each region.
72     constraint_sccs: Rc<Sccs<RegionVid, ConstraintSccIndex>>,
73
74     /// Reverse of the SCC constraint graph --  i.e., an edge `A -> B` exists if
75     /// `B: A`. This is used to compute the universal regions that are required
76     /// to outlive a given SCC. Computed lazily.
77     rev_scc_graph: Option<Rc<ReverseSccGraph>>,
78
79     /// The "R0 member of [R1..Rn]" constraints, indexed by SCC.
80     member_constraints: Rc<MemberConstraintSet<'tcx, ConstraintSccIndex>>,
81
82     /// Records the member constraints that we applied to each scc.
83     /// This is useful for error reporting. Once constraint
84     /// propagation is done, this vector is sorted according to
85     /// `member_region_scc`.
86     member_constraints_applied: Vec<AppliedMemberConstraint>,
87
88     /// Map universe indexes to information on why we created it.
89     universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
90
91     /// Contains the minimum universe of any variable within the same
92     /// SCC. We will ensure that no SCC contains values that are not
93     /// visible from this index.
94     scc_universes: IndexVec<ConstraintSccIndex, ty::UniverseIndex>,
95
96     /// Contains a "representative" from each SCC. This will be the
97     /// minimal RegionVid belonging to that universe. It is used as a
98     /// kind of hacky way to manage checking outlives relationships,
99     /// since we can 'canonicalize' each region to the representative
100     /// of its SCC and be sure that -- if they have the same repr --
101     /// they *must* be equal (though not having the same repr does not
102     /// mean they are unequal).
103     scc_representatives: IndexVec<ConstraintSccIndex, ty::RegionVid>,
104
105     /// The final inferred values of the region variables; we compute
106     /// one value per SCC. To get the value for any given *region*,
107     /// you first find which scc it is a part of.
108     scc_values: RegionValues<ConstraintSccIndex>,
109
110     /// Type constraints that we check after solving.
111     type_tests: Vec<TypeTest<'tcx>>,
112
113     /// Information about the universally quantified regions in scope
114     /// on this function.
115     universal_regions: Rc<UniversalRegions<'tcx>>,
116
117     /// Information about how the universally quantified regions in
118     /// scope on this function relate to one another.
119     universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
120 }
121
122 /// Each time that `apply_member_constraint` is successful, it appends
123 /// one of these structs to the `member_constraints_applied` field.
124 /// This is used in error reporting to trace out what happened.
125 ///
126 /// The way that `apply_member_constraint` works is that it effectively
127 /// adds a new lower bound to the SCC it is analyzing: so you wind up
128 /// with `'R: 'O` where `'R` is the pick-region and `'O` is the
129 /// minimal viable option.
130 #[derive(Debug)]
131 pub(crate) struct AppliedMemberConstraint {
132     /// The SCC that was affected. (The "member region".)
133     ///
134     /// The vector if `AppliedMemberConstraint` elements is kept sorted
135     /// by this field.
136     pub(crate) member_region_scc: ConstraintSccIndex,
137
138     /// The "best option" that `apply_member_constraint` found -- this was
139     /// added as an "ad-hoc" lower-bound to `member_region_scc`.
140     pub(crate) min_choice: ty::RegionVid,
141
142     /// The "member constraint index" -- we can find out details about
143     /// the constraint from
144     /// `set.member_constraints[member_constraint_index]`.
145     pub(crate) member_constraint_index: NllMemberConstraintIndex,
146 }
147
148 pub(crate) struct RegionDefinition<'tcx> {
149     /// What kind of variable is this -- a free region? existential
150     /// variable? etc. (See the `NllRegionVariableOrigin` for more
151     /// info.)
152     pub(crate) origin: NllRegionVariableOrigin,
153
154     /// Which universe is this region variable defined in? This is
155     /// most often `ty::UniverseIndex::ROOT`, but when we encounter
156     /// forall-quantifiers like `for<'a> { 'a = 'b }`, we would create
157     /// the variable for `'a` in a fresh universe that extends ROOT.
158     pub(crate) universe: ty::UniverseIndex,
159
160     /// If this is 'static or an early-bound region, then this is
161     /// `Some(X)` where `X` is the name of the region.
162     pub(crate) external_name: Option<ty::Region<'tcx>>,
163 }
164
165 /// N.B., the variants in `Cause` are intentionally ordered. Lower
166 /// values are preferred when it comes to error messages. Do not
167 /// reorder willy nilly.
168 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
169 pub(crate) enum Cause {
170     /// point inserted because Local was live at the given Location
171     LiveVar(Local, Location),
172
173     /// point inserted because Local was dropped at the given Location
174     DropVar(Local, Location),
175 }
176
177 /// A "type test" corresponds to an outlives constraint between a type
178 /// and a lifetime, like `T: 'x` or `<T as Foo>::Bar: 'x`. They are
179 /// translated from the `Verify` region constraints in the ordinary
180 /// inference context.
181 ///
182 /// These sorts of constraints are handled differently than ordinary
183 /// constraints, at least at present. During type checking, the
184 /// `InferCtxt::process_registered_region_obligations` method will
185 /// attempt to convert a type test like `T: 'x` into an ordinary
186 /// outlives constraint when possible (for example, `&'a T: 'b` will
187 /// be converted into `'a: 'b` and registered as a `Constraint`).
188 ///
189 /// In some cases, however, there are outlives relationships that are
190 /// not converted into a region constraint, but rather into one of
191 /// these "type tests". The distinction is that a type test does not
192 /// influence the inference result, but instead just examines the
193 /// values that we ultimately inferred for each region variable and
194 /// checks that they meet certain extra criteria. If not, an error
195 /// can be issued.
196 ///
197 /// One reason for this is that these type tests typically boil down
198 /// to a check like `'a: 'x` where `'a` is a universally quantified
199 /// region -- and therefore not one whose value is really meant to be
200 /// *inferred*, precisely (this is not always the case: one can have a
201 /// type test like `<Foo as Trait<'?0>>::Bar: 'x`, where `'?0` is an
202 /// inference variable). Another reason is that these type tests can
203 /// involve *disjunction* -- that is, they can be satisfied in more
204 /// than one way.
205 ///
206 /// For more information about this translation, see
207 /// `InferCtxt::process_registered_region_obligations` and
208 /// `InferCtxt::type_must_outlive` in `rustc_infer::infer::InferCtxt`.
209 #[derive(Clone, Debug)]
210 pub struct TypeTest<'tcx> {
211     /// The type `T` that must outlive the region.
212     pub generic_kind: GenericKind<'tcx>,
213
214     /// The region `'x` that the type must outlive.
215     pub lower_bound: RegionVid,
216
217     /// The span to blame.
218     pub span: Span,
219
220     /// A test which, if met by the region `'x`, proves that this type
221     /// constraint is satisfied.
222     pub verify_bound: VerifyBound<'tcx>,
223 }
224
225 /// When we have an unmet lifetime constraint, we try to propagate it outward (e.g. to a closure
226 /// environment). If we can't, it is an error.
227 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
228 enum RegionRelationCheckResult {
229     Ok,
230     Propagated,
231     Error,
232 }
233
234 #[derive(Clone, PartialEq, Eq, Debug)]
235 enum Trace<'tcx> {
236     StartRegion,
237     FromOutlivesConstraint(OutlivesConstraint<'tcx>),
238     NotVisited,
239 }
240
241 #[derive(Clone, PartialEq, Eq, Debug)]
242 pub enum ExtraConstraintInfo {
243     PlaceholderFromPredicate(Span),
244 }
245
246 impl<'tcx> RegionInferenceContext<'tcx> {
247     /// Creates a new region inference context with a total of
248     /// `num_region_variables` valid inference variables; the first N
249     /// of those will be constant regions representing the free
250     /// regions defined in `universal_regions`.
251     ///
252     /// The `outlives_constraints` and `type_tests` are an initial set
253     /// of constraints produced by the MIR type check.
254     pub(crate) fn new(
255         var_infos: VarInfos,
256         universal_regions: Rc<UniversalRegions<'tcx>>,
257         placeholder_indices: Rc<PlaceholderIndices>,
258         universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
259         outlives_constraints: OutlivesConstraintSet<'tcx>,
260         member_constraints_in: MemberConstraintSet<'tcx, RegionVid>,
261         universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
262         type_tests: Vec<TypeTest<'tcx>>,
263         liveness_constraints: LivenessValues<RegionVid>,
264         elements: &Rc<RegionValueElements>,
265     ) -> Self {
266         // Create a RegionDefinition for each inference variable.
267         let definitions: IndexVec<_, _> = var_infos
268             .iter()
269             .map(|info| RegionDefinition::new(info.universe, info.origin))
270             .collect();
271
272         let constraints = Frozen::freeze(outlives_constraints);
273         let constraint_graph = Frozen::freeze(constraints.graph(definitions.len()));
274         let fr_static = universal_regions.fr_static;
275         let constraint_sccs = Rc::new(constraints.compute_sccs(&constraint_graph, fr_static));
276
277         let mut scc_values =
278             RegionValues::new(elements, universal_regions.len(), &placeholder_indices);
279
280         for region in liveness_constraints.rows() {
281             let scc = constraint_sccs.scc(region);
282             scc_values.merge_liveness(scc, region, &liveness_constraints);
283         }
284
285         let scc_universes = Self::compute_scc_universes(&constraint_sccs, &definitions);
286
287         let scc_representatives = Self::compute_scc_representatives(&constraint_sccs, &definitions);
288
289         let member_constraints =
290             Rc::new(member_constraints_in.into_mapped(|r| constraint_sccs.scc(r)));
291
292         let mut result = Self {
293             var_infos,
294             definitions,
295             liveness_constraints,
296             constraints,
297             constraint_graph,
298             constraint_sccs,
299             rev_scc_graph: None,
300             member_constraints,
301             member_constraints_applied: Vec::new(),
302             universe_causes,
303             scc_universes,
304             scc_representatives,
305             scc_values,
306             type_tests,
307             universal_regions,
308             universal_region_relations,
309         };
310
311         result.init_free_and_bound_regions();
312
313         result
314     }
315
316     /// Each SCC is the combination of many region variables which
317     /// have been equated. Therefore, we can associate a universe with
318     /// each SCC which is minimum of all the universes of its
319     /// constituent regions -- this is because whatever value the SCC
320     /// takes on must be a value that each of the regions within the
321     /// SCC could have as well. This implies that the SCC must have
322     /// the minimum, or narrowest, universe.
323     fn compute_scc_universes(
324         constraint_sccs: &Sccs<RegionVid, ConstraintSccIndex>,
325         definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
326     ) -> IndexVec<ConstraintSccIndex, ty::UniverseIndex> {
327         let num_sccs = constraint_sccs.num_sccs();
328         let mut scc_universes = IndexVec::from_elem_n(ty::UniverseIndex::MAX, num_sccs);
329
330         debug!("compute_scc_universes()");
331
332         // For each region R in universe U, ensure that the universe for the SCC
333         // that contains R is "no bigger" than U. This effectively sets the universe
334         // for each SCC to be the minimum of the regions within.
335         for (region_vid, region_definition) in definitions.iter_enumerated() {
336             let scc = constraint_sccs.scc(region_vid);
337             let scc_universe = &mut scc_universes[scc];
338             let scc_min = std::cmp::min(region_definition.universe, *scc_universe);
339             if scc_min != *scc_universe {
340                 *scc_universe = scc_min;
341                 debug!(
342                     "compute_scc_universes: lowered universe of {scc:?} to {scc_min:?} \
343                     because it contains {region_vid:?} in {region_universe:?}",
344                     scc = scc,
345                     scc_min = scc_min,
346                     region_vid = region_vid,
347                     region_universe = region_definition.universe,
348                 );
349             }
350         }
351
352         // Walk each SCC `A` and `B` such that `A: B`
353         // and ensure that universe(A) can see universe(B).
354         //
355         // This serves to enforce the 'empty/placeholder' hierarchy
356         // (described in more detail on `RegionKind`):
357         //
358         // ```
359         // static -----+
360         //   |         |
361         // empty(U0) placeholder(U1)
362         //   |      /
363         // empty(U1)
364         // ```
365         //
366         // In particular, imagine we have variables R0 in U0 and R1
367         // created in U1, and constraints like this;
368         //
369         // ```
370         // R1: !1 // R1 outlives the placeholder in U1
371         // R1: R0 // R1 outlives R0
372         // ```
373         //
374         // Here, we wish for R1 to be `'static`, because it
375         // cannot outlive `placeholder(U1)` and `empty(U0)` any other way.
376         //
377         // Thanks to this loop, what happens is that the `R1: R0`
378         // constraint lowers the universe of `R1` to `U0`, which in turn
379         // means that the `R1: !1` constraint will (later) cause
380         // `R1` to become `'static`.
381         for scc_a in constraint_sccs.all_sccs() {
382             for &scc_b in constraint_sccs.successors(scc_a) {
383                 let scc_universe_a = scc_universes[scc_a];
384                 let scc_universe_b = scc_universes[scc_b];
385                 let scc_universe_min = std::cmp::min(scc_universe_a, scc_universe_b);
386                 if scc_universe_a != scc_universe_min {
387                     scc_universes[scc_a] = scc_universe_min;
388
389                     debug!(
390                         "compute_scc_universes: lowered universe of {scc_a:?} to {scc_universe_min:?} \
391                         because {scc_a:?}: {scc_b:?} and {scc_b:?} is in universe {scc_universe_b:?}",
392                         scc_a = scc_a,
393                         scc_b = scc_b,
394                         scc_universe_min = scc_universe_min,
395                         scc_universe_b = scc_universe_b
396                     );
397                 }
398             }
399         }
400
401         debug!("compute_scc_universes: scc_universe = {:#?}", scc_universes);
402
403         scc_universes
404     }
405
406     /// For each SCC, we compute a unique `RegionVid` (in fact, the
407     /// minimal one that belongs to the SCC). See
408     /// `scc_representatives` field of `RegionInferenceContext` for
409     /// more details.
410     fn compute_scc_representatives(
411         constraints_scc: &Sccs<RegionVid, ConstraintSccIndex>,
412         definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
413     ) -> IndexVec<ConstraintSccIndex, ty::RegionVid> {
414         let num_sccs = constraints_scc.num_sccs();
415         let next_region_vid = definitions.next_index();
416         let mut scc_representatives = IndexVec::from_elem_n(next_region_vid, num_sccs);
417
418         for region_vid in definitions.indices() {
419             let scc = constraints_scc.scc(region_vid);
420             let prev_min = scc_representatives[scc];
421             scc_representatives[scc] = region_vid.min(prev_min);
422         }
423
424         scc_representatives
425     }
426
427     /// Initializes the region variables for each universally
428     /// quantified region (lifetime parameter). The first N variables
429     /// always correspond to the regions appearing in the function
430     /// signature (both named and anonymous) and where-clauses. This
431     /// function iterates over those regions and initializes them with
432     /// minimum values.
433     ///
434     /// For example:
435     /// ```
436     /// fn foo<'a, 'b>( /* ... */ ) where 'a: 'b { /* ... */ }
437     /// ```
438     /// would initialize two variables like so:
439     /// ```ignore (illustrative)
440     /// R0 = { CFG, R0 } // 'a
441     /// R1 = { CFG, R0, R1 } // 'b
442     /// ```
443     /// Here, R0 represents `'a`, and it contains (a) the entire CFG
444     /// and (b) any universally quantified regions that it outlives,
445     /// which in this case is just itself. R1 (`'b`) in contrast also
446     /// outlives `'a` and hence contains R0 and R1.
447     fn init_free_and_bound_regions(&mut self) {
448         // Update the names (if any)
449         for (external_name, variable) in self.universal_regions.named_universal_regions() {
450             debug!(
451                 "init_universal_regions: region {:?} has external name {:?}",
452                 variable, external_name
453             );
454             self.definitions[variable].external_name = Some(external_name);
455         }
456
457         for variable in self.definitions.indices() {
458             let scc = self.constraint_sccs.scc(variable);
459
460             match self.definitions[variable].origin {
461                 NllRegionVariableOrigin::FreeRegion => {
462                     // For each free, universally quantified region X:
463
464                     // Add all nodes in the CFG to liveness constraints
465                     self.liveness_constraints.add_all_points(variable);
466                     self.scc_values.add_all_points(scc);
467
468                     // Add `end(X)` into the set for X.
469                     self.scc_values.add_element(scc, variable);
470                 }
471
472                 NllRegionVariableOrigin::Placeholder(placeholder) => {
473                     // Each placeholder region is only visible from
474                     // its universe `ui` and its extensions. So we
475                     // can't just add it into `scc` unless the
476                     // universe of the scc can name this region.
477                     let scc_universe = self.scc_universes[scc];
478                     if scc_universe.can_name(placeholder.universe) {
479                         self.scc_values.add_element(scc, placeholder);
480                     } else {
481                         debug!(
482                             "init_free_and_bound_regions: placeholder {:?} is \
483                              not compatible with universe {:?} of its SCC {:?}",
484                             placeholder, scc_universe, scc,
485                         );
486                         self.add_incompatible_universe(scc);
487                     }
488                 }
489
490                 NllRegionVariableOrigin::Existential { .. } => {
491                     // For existential, regions, nothing to do.
492                 }
493             }
494         }
495     }
496
497     /// Returns an iterator over all the region indices.
498     pub fn regions(&self) -> impl Iterator<Item = RegionVid> + 'tcx {
499         self.definitions.indices()
500     }
501
502     /// Given a universal region in scope on the MIR, returns the
503     /// corresponding index.
504     ///
505     /// (Panics if `r` is not a registered universal region.)
506     pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
507         self.universal_regions.to_region_vid(r)
508     }
509
510     /// Adds annotations for `#[rustc_regions]`; see `UniversalRegions::annotate`.
511     pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diagnostic) {
512         self.universal_regions.annotate(tcx, err)
513     }
514
515     /// Returns `true` if the region `r` contains the point `p`.
516     ///
517     /// Panics if called before `solve()` executes,
518     pub(crate) fn region_contains(&self, r: impl ToRegionVid, p: impl ToElementIndex) -> bool {
519         let scc = self.constraint_sccs.scc(r.to_region_vid());
520         self.scc_values.contains(scc, p)
521     }
522
523     /// Returns access to the value of `r` for debugging purposes.
524     pub(crate) fn region_value_str(&self, r: RegionVid) -> String {
525         let scc = self.constraint_sccs.scc(r.to_region_vid());
526         self.scc_values.region_value_str(scc)
527     }
528
529     pub(crate) fn placeholders_contained_in<'a>(
530         &'a self,
531         r: RegionVid,
532     ) -> impl Iterator<Item = ty::PlaceholderRegion> + 'a {
533         let scc = self.constraint_sccs.scc(r.to_region_vid());
534         self.scc_values.placeholders_contained_in(scc)
535     }
536
537     /// Returns access to the value of `r` for debugging purposes.
538     pub(crate) fn region_universe(&self, r: RegionVid) -> ty::UniverseIndex {
539         let scc = self.constraint_sccs.scc(r.to_region_vid());
540         self.scc_universes[scc]
541     }
542
543     /// Once region solving has completed, this function will return
544     /// the member constraints that were applied to the value of a given
545     /// region `r`. See `AppliedMemberConstraint`.
546     pub(crate) fn applied_member_constraints(
547         &self,
548         r: impl ToRegionVid,
549     ) -> &[AppliedMemberConstraint] {
550         let scc = self.constraint_sccs.scc(r.to_region_vid());
551         binary_search_util::binary_search_slice(
552             &self.member_constraints_applied,
553             |applied| applied.member_region_scc,
554             &scc,
555         )
556     }
557
558     /// Performs region inference and report errors if we see any
559     /// unsatisfiable constraints. If this is a closure, returns the
560     /// region requirements to propagate to our creator, if any.
561     #[instrument(skip(self, infcx, body, polonius_output), level = "debug")]
562     pub(super) fn solve(
563         &mut self,
564         infcx: &InferCtxt<'tcx>,
565         param_env: ty::ParamEnv<'tcx>,
566         body: &Body<'tcx>,
567         polonius_output: Option<Rc<PoloniusOutput>>,
568     ) -> (Option<ClosureRegionRequirements<'tcx>>, RegionErrors<'tcx>) {
569         let mir_def_id = body.source.def_id();
570         self.propagate_constraints(body);
571
572         let mut errors_buffer = RegionErrors::new(infcx.tcx);
573
574         // If this is a closure, we can propagate unsatisfied
575         // `outlives_requirements` to our creator, so create a vector
576         // to store those. Otherwise, we'll pass in `None` to the
577         // functions below, which will trigger them to report errors
578         // eagerly.
579         let mut outlives_requirements = infcx.tcx.is_typeck_child(mir_def_id).then(Vec::new);
580
581         self.check_type_tests(
582             infcx,
583             param_env,
584             body,
585             outlives_requirements.as_mut(),
586             &mut errors_buffer,
587         );
588
589         // In Polonius mode, the errors about missing universal region relations are in the output
590         // and need to be emitted or propagated. Otherwise, we need to check whether the
591         // constraints were too strong, and if so, emit or propagate those errors.
592         if infcx.tcx.sess.opts.unstable_opts.polonius {
593             self.check_polonius_subset_errors(
594                 outlives_requirements.as_mut(),
595                 &mut errors_buffer,
596                 polonius_output.expect("Polonius output is unavailable despite `-Z polonius`"),
597             );
598         } else {
599             self.check_universal_regions(outlives_requirements.as_mut(), &mut errors_buffer);
600         }
601
602         if errors_buffer.is_empty() {
603             self.check_member_constraints(infcx, &mut errors_buffer);
604         }
605
606         let outlives_requirements = outlives_requirements.unwrap_or_default();
607
608         if outlives_requirements.is_empty() {
609             (None, errors_buffer)
610         } else {
611             let num_external_vids = self.universal_regions.num_global_and_external_regions();
612             (
613                 Some(ClosureRegionRequirements { num_external_vids, outlives_requirements }),
614                 errors_buffer,
615             )
616         }
617     }
618
619     /// Propagate the region constraints: this will grow the values
620     /// for each region variable until all the constraints are
621     /// satisfied. Note that some values may grow **too** large to be
622     /// feasible, but we check this later.
623     #[instrument(skip(self, _body), level = "debug")]
624     fn propagate_constraints(&mut self, _body: &Body<'tcx>) {
625         debug!("constraints={:#?}", {
626             let mut constraints: Vec<_> = self.constraints.outlives().iter().collect();
627             constraints.sort_by_key(|c| (c.sup, c.sub));
628             constraints
629                 .into_iter()
630                 .map(|c| (c, self.constraint_sccs.scc(c.sup), self.constraint_sccs.scc(c.sub)))
631                 .collect::<Vec<_>>()
632         });
633
634         // To propagate constraints, we walk the DAG induced by the
635         // SCC. For each SCC, we visit its successors and compute
636         // their values, then we union all those values to get our
637         // own.
638         let constraint_sccs = self.constraint_sccs.clone();
639         for scc in constraint_sccs.all_sccs() {
640             self.compute_value_for_scc(scc);
641         }
642
643         // Sort the applied member constraints so we can binary search
644         // through them later.
645         self.member_constraints_applied.sort_by_key(|applied| applied.member_region_scc);
646     }
647
648     /// Computes the value of the SCC `scc_a`, which has not yet been
649     /// computed, by unioning the values of its successors.
650     /// Assumes that all successors have been computed already
651     /// (which is assured by iterating over SCCs in dependency order).
652     #[instrument(skip(self), level = "debug")]
653     fn compute_value_for_scc(&mut self, scc_a: ConstraintSccIndex) {
654         let constraint_sccs = self.constraint_sccs.clone();
655
656         // Walk each SCC `B` such that `A: B`...
657         for &scc_b in constraint_sccs.successors(scc_a) {
658             debug!(?scc_b);
659
660             // ...and add elements from `B` into `A`. One complication
661             // arises because of universes: If `B` contains something
662             // that `A` cannot name, then `A` can only contain `B` if
663             // it outlives static.
664             if self.universe_compatible(scc_b, scc_a) {
665                 // `A` can name everything that is in `B`, so just
666                 // merge the bits.
667                 self.scc_values.add_region(scc_a, scc_b);
668             } else {
669                 self.add_incompatible_universe(scc_a);
670             }
671         }
672
673         // Now take member constraints into account.
674         let member_constraints = self.member_constraints.clone();
675         for m_c_i in member_constraints.indices(scc_a) {
676             self.apply_member_constraint(scc_a, m_c_i, member_constraints.choice_regions(m_c_i));
677         }
678
679         debug!(value = ?self.scc_values.region_value_str(scc_a));
680     }
681
682     /// Invoked for each `R0 member of [R1..Rn]` constraint.
683     ///
684     /// `scc` is the SCC containing R0, and `choice_regions` are the
685     /// `R1..Rn` regions -- they are always known to be universal
686     /// regions (and if that's not true, we just don't attempt to
687     /// enforce the constraint).
688     ///
689     /// The current value of `scc` at the time the method is invoked
690     /// is considered a *lower bound*. If possible, we will modify
691     /// the constraint to set it equal to one of the option regions.
692     /// If we make any changes, returns true, else false.
693     #[instrument(skip(self, member_constraint_index), level = "debug")]
694     fn apply_member_constraint(
695         &mut self,
696         scc: ConstraintSccIndex,
697         member_constraint_index: NllMemberConstraintIndex,
698         choice_regions: &[ty::RegionVid],
699     ) -> bool {
700         // Create a mutable vector of the options. We'll try to winnow
701         // them down.
702         let mut choice_regions: Vec<ty::RegionVid> = choice_regions.to_vec();
703
704         // Convert to the SCC representative: sometimes we have inference
705         // variables in the member constraint that wind up equated with
706         // universal regions. The scc representative is the minimal numbered
707         // one from the corresponding scc so it will be the universal region
708         // if one exists.
709         for c_r in &mut choice_regions {
710             let scc = self.constraint_sccs.scc(*c_r);
711             *c_r = self.scc_representatives[scc];
712         }
713
714         // The 'member region' in a member constraint is part of the
715         // hidden type, which must be in the root universe. Therefore,
716         // it cannot have any placeholders in its value.
717         assert!(self.scc_universes[scc] == ty::UniverseIndex::ROOT);
718         debug_assert!(
719             self.scc_values.placeholders_contained_in(scc).next().is_none(),
720             "scc {:?} in a member constraint has placeholder value: {:?}",
721             scc,
722             self.scc_values.region_value_str(scc),
723         );
724
725         // The existing value for `scc` is a lower-bound. This will
726         // consist of some set `{P} + {LB}` of points `{P}` and
727         // lower-bound free regions `{LB}`. As each choice region `O`
728         // is a free region, it will outlive the points. But we can
729         // only consider the option `O` if `O: LB`.
730         choice_regions.retain(|&o_r| {
731             self.scc_values
732                 .universal_regions_outlived_by(scc)
733                 .all(|lb| self.universal_region_relations.outlives(o_r, lb))
734         });
735         debug!(?choice_regions, "after lb");
736
737         // Now find all the *upper bounds* -- that is, each UB is a
738         // free region that must outlive the member region `R0` (`UB:
739         // R0`). Therefore, we need only keep an option `O` if `UB: O`
740         // for all UB.
741         let rev_scc_graph = self.reverse_scc_graph();
742         let universal_region_relations = &self.universal_region_relations;
743         for ub in rev_scc_graph.upper_bounds(scc) {
744             debug!(?ub);
745             choice_regions.retain(|&o_r| universal_region_relations.outlives(ub, o_r));
746         }
747         debug!(?choice_regions, "after ub");
748
749         // If we ruled everything out, we're done.
750         if choice_regions.is_empty() {
751             return false;
752         }
753
754         // Otherwise, we need to find the minimum remaining choice, if
755         // any, and take that.
756         debug!("choice_regions remaining are {:#?}", choice_regions);
757         let Some(&min_choice) = choice_regions.iter().find(|&r1| {
758             choice_regions.iter().all(|&r2| {
759                 self.universal_region_relations.outlives(r2, *r1)
760             })
761         }) else {
762             debug!("no choice region outlived by all others");
763             return false;
764         };
765
766         let min_choice_scc = self.constraint_sccs.scc(min_choice);
767         debug!(?min_choice, ?min_choice_scc);
768         if self.scc_values.add_region(scc, min_choice_scc) {
769             self.member_constraints_applied.push(AppliedMemberConstraint {
770                 member_region_scc: scc,
771                 min_choice,
772                 member_constraint_index,
773             });
774
775             true
776         } else {
777             false
778         }
779     }
780
781     /// Returns `true` if all the elements in the value of `scc_b` are nameable
782     /// in `scc_a`. Used during constraint propagation, and only once
783     /// the value of `scc_b` has been computed.
784     fn universe_compatible(&self, scc_b: ConstraintSccIndex, scc_a: ConstraintSccIndex) -> bool {
785         let universe_a = self.scc_universes[scc_a];
786
787         // Quick check: if scc_b's declared universe is a subset of
788         // scc_a's declared universe (typically, both are ROOT), then
789         // it cannot contain any problematic universe elements.
790         if universe_a.can_name(self.scc_universes[scc_b]) {
791             return true;
792         }
793
794         // Otherwise, we have to iterate over the universe elements in
795         // B's value, and check whether all of them are nameable
796         // from universe_a
797         self.scc_values.placeholders_contained_in(scc_b).all(|p| universe_a.can_name(p.universe))
798     }
799
800     /// Extend `scc` so that it can outlive some placeholder region
801     /// from a universe it can't name; at present, the only way for
802     /// this to be true is if `scc` outlives `'static`. This is
803     /// actually stricter than necessary: ideally, we'd support bounds
804     /// like `for<'a: 'b`>` that might then allow us to approximate
805     /// `'a` with `'b` and not `'static`. But it will have to do for
806     /// now.
807     fn add_incompatible_universe(&mut self, scc: ConstraintSccIndex) {
808         debug!("add_incompatible_universe(scc={:?})", scc);
809
810         let fr_static = self.universal_regions.fr_static;
811         self.scc_values.add_all_points(scc);
812         self.scc_values.add_element(scc, fr_static);
813     }
814
815     /// Once regions have been propagated, this method is used to see
816     /// whether the "type tests" produced by typeck were satisfied;
817     /// type tests encode type-outlives relationships like `T:
818     /// 'a`. See `TypeTest` for more details.
819     fn check_type_tests(
820         &self,
821         infcx: &InferCtxt<'tcx>,
822         param_env: ty::ParamEnv<'tcx>,
823         body: &Body<'tcx>,
824         mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
825         errors_buffer: &mut RegionErrors<'tcx>,
826     ) {
827         let tcx = infcx.tcx;
828
829         // Sometimes we register equivalent type-tests that would
830         // result in basically the exact same error being reported to
831         // the user. Avoid that.
832         let mut deduplicate_errors = FxHashSet::default();
833
834         for type_test in &self.type_tests {
835             debug!("check_type_test: {:?}", type_test);
836
837             let generic_ty = type_test.generic_kind.to_ty(tcx);
838             if self.eval_verify_bound(
839                 infcx,
840                 param_env,
841                 generic_ty,
842                 type_test.lower_bound,
843                 &type_test.verify_bound,
844             ) {
845                 continue;
846             }
847
848             if let Some(propagated_outlives_requirements) = &mut propagated_outlives_requirements {
849                 if self.try_promote_type_test(
850                     infcx,
851                     param_env,
852                     body,
853                     type_test,
854                     propagated_outlives_requirements,
855                 ) {
856                     continue;
857                 }
858             }
859
860             // Type-test failed. Report the error.
861             let erased_generic_kind = infcx.tcx.erase_regions(type_test.generic_kind);
862
863             // Skip duplicate-ish errors.
864             if deduplicate_errors.insert((
865                 erased_generic_kind,
866                 type_test.lower_bound,
867                 type_test.span,
868             )) {
869                 debug!(
870                     "check_type_test: reporting error for erased_generic_kind={:?}, \
871                      lower_bound_region={:?}, \
872                      type_test.span={:?}",
873                     erased_generic_kind, type_test.lower_bound, type_test.span,
874                 );
875
876                 errors_buffer.push(RegionErrorKind::TypeTestError { type_test: type_test.clone() });
877             }
878         }
879     }
880
881     /// Invoked when we have some type-test (e.g., `T: 'X`) that we cannot
882     /// prove to be satisfied. If this is a closure, we will attempt to
883     /// "promote" this type-test into our `ClosureRegionRequirements` and
884     /// hence pass it up the creator. To do this, we have to phrase the
885     /// type-test in terms of external free regions, as local free
886     /// regions are not nameable by the closure's creator.
887     ///
888     /// Promotion works as follows: we first check that the type `T`
889     /// contains only regions that the creator knows about. If this is
890     /// true, then -- as a consequence -- we know that all regions in
891     /// the type `T` are free regions that outlive the closure body. If
892     /// false, then promotion fails.
893     ///
894     /// Once we've promoted T, we have to "promote" `'X` to some region
895     /// that is "external" to the closure. Generally speaking, a region
896     /// may be the union of some points in the closure body as well as
897     /// various free lifetimes. We can ignore the points in the closure
898     /// body: if the type T can be expressed in terms of external regions,
899     /// we know it outlives the points in the closure body. That
900     /// just leaves the free regions.
901     ///
902     /// The idea then is to lower the `T: 'X` constraint into multiple
903     /// bounds -- e.g., if `'X` is the union of two free lifetimes,
904     /// `'1` and `'2`, then we would create `T: '1` and `T: '2`.
905     #[instrument(level = "debug", skip(self, infcx, propagated_outlives_requirements))]
906     fn try_promote_type_test(
907         &self,
908         infcx: &InferCtxt<'tcx>,
909         param_env: ty::ParamEnv<'tcx>,
910         body: &Body<'tcx>,
911         type_test: &TypeTest<'tcx>,
912         propagated_outlives_requirements: &mut Vec<ClosureOutlivesRequirement<'tcx>>,
913     ) -> bool {
914         let tcx = infcx.tcx;
915
916         let TypeTest { generic_kind, lower_bound, span: _, verify_bound: _ } = type_test;
917
918         let generic_ty = generic_kind.to_ty(tcx);
919         let Some(subject) = self.try_promote_type_test_subject(infcx, generic_ty) else {
920             return false;
921         };
922
923         debug!("subject = {:?}", subject);
924
925         let r_scc = self.constraint_sccs.scc(*lower_bound);
926
927         debug!(
928             "lower_bound = {:?} r_scc={:?} universe={:?}",
929             lower_bound, r_scc, self.scc_universes[r_scc]
930         );
931
932         // If the type test requires that `T: 'a` where `'a` is a
933         // placeholder from another universe, that effectively requires
934         // `T: 'static`, so we have to propagate that requirement.
935         //
936         // It doesn't matter *what* universe because the promoted `T` will
937         // always be in the root universe.
938         if let Some(p) = self.scc_values.placeholders_contained_in(r_scc).next() {
939             debug!("encountered placeholder in higher universe: {:?}, requiring 'static", p);
940             let static_r = self.universal_regions.fr_static;
941             propagated_outlives_requirements.push(ClosureOutlivesRequirement {
942                 subject,
943                 outlived_free_region: static_r,
944                 blame_span: type_test.span,
945                 category: ConstraintCategory::Boring,
946             });
947
948             // we can return here -- the code below might push add'l constraints
949             // but they would all be weaker than this one.
950             return true;
951         }
952
953         // For each region outlived by lower_bound find a non-local,
954         // universal region (it may be the same region) and add it to
955         // `ClosureOutlivesRequirement`.
956         for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
957             debug!("universal_region_outlived_by ur={:?}", ur);
958             // Check whether we can already prove that the "subject" outlives `ur`.
959             // If so, we don't have to propagate this requirement to our caller.
960             //
961             // To continue the example from the function, if we are trying to promote
962             // a requirement that `T: 'X`, and we know that `'X = '1 + '2` (i.e., the union
963             // `'1` and `'2`), then in this loop `ur` will be `'1` (and `'2`). So here
964             // we check whether `T: '1` is something we *can* prove. If so, no need
965             // to propagate that requirement.
966             //
967             // This is needed because -- particularly in the case
968             // where `ur` is a local bound -- we are sometimes in a
969             // position to prove things that our caller cannot. See
970             // #53570 for an example.
971             if self.eval_verify_bound(infcx, param_env, generic_ty, ur, &type_test.verify_bound) {
972                 continue;
973             }
974
975             let non_local_ub = self.universal_region_relations.non_local_upper_bounds(ur);
976             debug!("try_promote_type_test: non_local_ub={:?}", non_local_ub);
977
978             // This is slightly too conservative. To show T: '1, given `'2: '1`
979             // and `'3: '1` we only need to prove that T: '2 *or* T: '3, but to
980             // avoid potential non-determinism we approximate this by requiring
981             // T: '1 and T: '2.
982             for upper_bound in non_local_ub {
983                 debug_assert!(self.universal_regions.is_universal_region(upper_bound));
984                 debug_assert!(!self.universal_regions.is_local_free_region(upper_bound));
985
986                 let requirement = ClosureOutlivesRequirement {
987                     subject,
988                     outlived_free_region: upper_bound,
989                     blame_span: type_test.span,
990                     category: ConstraintCategory::Boring,
991                 };
992                 debug!("try_promote_type_test: pushing {:#?}", requirement);
993                 propagated_outlives_requirements.push(requirement);
994             }
995         }
996         true
997     }
998
999     /// When we promote a type test `T: 'r`, we have to convert the
1000     /// type `T` into something we can store in a query result (so
1001     /// something allocated for `'tcx`). This is problematic if `ty`
1002     /// contains regions. During the course of NLL region checking, we
1003     /// will have replaced all of those regions with fresh inference
1004     /// variables. To create a test subject, we want to replace those
1005     /// inference variables with some region from the closure
1006     /// signature -- this is not always possible, so this is a
1007     /// fallible process. Presuming we do find a suitable region, we
1008     /// will use it's *external name*, which will be a `RegionKind`
1009     /// variant that can be used in query responses such as
1010     /// `ReEarlyBound`.
1011     #[instrument(level = "debug", skip(self, infcx))]
1012     fn try_promote_type_test_subject(
1013         &self,
1014         infcx: &InferCtxt<'tcx>,
1015         ty: Ty<'tcx>,
1016     ) -> Option<ClosureOutlivesSubject<'tcx>> {
1017         let tcx = infcx.tcx;
1018
1019         let ty = tcx.fold_regions(ty, |r, _depth| {
1020             let region_vid = self.to_region_vid(r);
1021
1022             // The challenge if this. We have some region variable `r`
1023             // whose value is a set of CFG points and universal
1024             // regions. We want to find if that set is *equivalent* to
1025             // any of the named regions found in the closure.
1026             //
1027             // To do so, we compute the
1028             // `non_local_universal_upper_bound`. This will be a
1029             // non-local, universal region that is greater than `r`.
1030             // However, it might not be *contained* within `r`, so
1031             // then we further check whether this bound is contained
1032             // in `r`. If so, we can say that `r` is equivalent to the
1033             // bound.
1034             //
1035             // Let's work through a few examples. For these, imagine
1036             // that we have 3 non-local regions (I'll denote them as
1037             // `'static`, `'a`, and `'b`, though of course in the code
1038             // they would be represented with indices) where:
1039             //
1040             // - `'static: 'a`
1041             // - `'static: 'b`
1042             //
1043             // First, let's assume that `r` is some existential
1044             // variable with an inferred value `{'a, 'static}` (plus
1045             // some CFG nodes). In this case, the non-local upper
1046             // bound is `'static`, since that outlives `'a`. `'static`
1047             // is also a member of `r` and hence we consider `r`
1048             // equivalent to `'static` (and replace it with
1049             // `'static`).
1050             //
1051             // Now let's consider the inferred value `{'a, 'b}`. This
1052             // means `r` is effectively `'a | 'b`. I'm not sure if
1053             // this can come about, actually, but assuming it did, we
1054             // would get a non-local upper bound of `'static`. Since
1055             // `'static` is not contained in `r`, we would fail to
1056             // find an equivalent.
1057             let upper_bound = self.non_local_universal_upper_bound(region_vid);
1058             if self.region_contains(region_vid, upper_bound) {
1059                 self.definitions[upper_bound].external_name.unwrap_or(r)
1060             } else {
1061                 // In the case of a failure, use a `ReVar` result. This will
1062                 // cause the `needs_infer` later on to return `None`.
1063                 r
1064             }
1065         });
1066
1067         debug!("try_promote_type_test_subject: folded ty = {:?}", ty);
1068
1069         // `needs_infer` will only be true if we failed to promote some region.
1070         if ty.needs_infer() {
1071             return None;
1072         }
1073
1074         Some(ClosureOutlivesSubject::Ty(ty))
1075     }
1076
1077     /// Given some universal or existential region `r`, finds a
1078     /// non-local, universal region `r+` that outlives `r` at entry to (and
1079     /// exit from) the closure. In the worst case, this will be
1080     /// `'static`.
1081     ///
1082     /// This is used for two purposes. First, if we are propagated
1083     /// some requirement `T: r`, we can use this method to enlarge `r`
1084     /// to something we can encode for our creator (which only knows
1085     /// about non-local, universal regions). It is also used when
1086     /// encoding `T` as part of `try_promote_type_test_subject` (see
1087     /// that fn for details).
1088     ///
1089     /// This is based on the result `'y` of `universal_upper_bound`,
1090     /// except that it converts further takes the non-local upper
1091     /// bound of `'y`, so that the final result is non-local.
1092     fn non_local_universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1093         debug!("non_local_universal_upper_bound(r={:?}={})", r, self.region_value_str(r));
1094
1095         let lub = self.universal_upper_bound(r);
1096
1097         // Grow further to get smallest universal region known to
1098         // creator.
1099         let non_local_lub = self.universal_region_relations.non_local_upper_bound(lub);
1100
1101         debug!("non_local_universal_upper_bound: non_local_lub={:?}", non_local_lub);
1102
1103         non_local_lub
1104     }
1105
1106     /// Returns a universally quantified region that outlives the
1107     /// value of `r` (`r` may be existentially or universally
1108     /// quantified).
1109     ///
1110     /// Since `r` is (potentially) an existential region, it has some
1111     /// value which may include (a) any number of points in the CFG
1112     /// and (b) any number of `end('x)` elements of universally
1113     /// quantified regions. To convert this into a single universal
1114     /// region we do as follows:
1115     ///
1116     /// - Ignore the CFG points in `'r`. All universally quantified regions
1117     ///   include the CFG anyhow.
1118     /// - For each `end('x)` element in `'r`, compute the mutual LUB, yielding
1119     ///   a result `'y`.
1120     #[instrument(skip(self), level = "debug", ret)]
1121     pub(crate) fn universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1122         debug!(r = %self.region_value_str(r));
1123
1124         // Find the smallest universal region that contains all other
1125         // universal regions within `region`.
1126         let mut lub = self.universal_regions.fr_fn_body;
1127         let r_scc = self.constraint_sccs.scc(r);
1128         for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
1129             lub = self.universal_region_relations.postdom_upper_bound(lub, ur);
1130         }
1131
1132         lub
1133     }
1134
1135     /// Like `universal_upper_bound`, but returns an approximation more suitable
1136     /// for diagnostics. If `r` contains multiple disjoint universal regions
1137     /// (e.g. 'a and 'b in `fn foo<'a, 'b> { ... }`, we pick the lower-numbered region.
1138     /// This corresponds to picking named regions over unnamed regions
1139     /// (e.g. picking early-bound regions over a closure late-bound region).
1140     ///
1141     /// This means that the returned value may not be a true upper bound, since
1142     /// only 'static is known to outlive disjoint universal regions.
1143     /// Therefore, this method should only be used in diagnostic code,
1144     /// where displaying *some* named universal region is better than
1145     /// falling back to 'static.
1146     #[instrument(level = "debug", skip(self))]
1147     pub(crate) fn approx_universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1148         debug!("{}", self.region_value_str(r));
1149
1150         // Find the smallest universal region that contains all other
1151         // universal regions within `region`.
1152         let mut lub = self.universal_regions.fr_fn_body;
1153         let r_scc = self.constraint_sccs.scc(r);
1154         let static_r = self.universal_regions.fr_static;
1155         for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
1156             let new_lub = self.universal_region_relations.postdom_upper_bound(lub, ur);
1157             debug!(?ur, ?lub, ?new_lub);
1158             // The upper bound of two non-static regions is static: this
1159             // means we know nothing about the relationship between these
1160             // two regions. Pick a 'better' one to use when constructing
1161             // a diagnostic
1162             if ur != static_r && lub != static_r && new_lub == static_r {
1163                 // Prefer the region with an `external_name` - this
1164                 // indicates that the region is early-bound, so working with
1165                 // it can produce a nicer error.
1166                 if self.region_definition(ur).external_name.is_some() {
1167                     lub = ur;
1168                 } else if self.region_definition(lub).external_name.is_some() {
1169                     // Leave lub unchanged
1170                 } else {
1171                     // If we get here, we don't have any reason to prefer
1172                     // one region over the other. Just pick the
1173                     // one with the lower index for now.
1174                     lub = std::cmp::min(ur, lub);
1175                 }
1176             } else {
1177                 lub = new_lub;
1178             }
1179         }
1180
1181         debug!(?r, ?lub);
1182
1183         lub
1184     }
1185
1186     /// Tests if `test` is true when applied to `lower_bound` at
1187     /// `point`.
1188     fn eval_verify_bound(
1189         &self,
1190         infcx: &InferCtxt<'tcx>,
1191         param_env: ty::ParamEnv<'tcx>,
1192         generic_ty: Ty<'tcx>,
1193         lower_bound: RegionVid,
1194         verify_bound: &VerifyBound<'tcx>,
1195     ) -> bool {
1196         debug!("eval_verify_bound(lower_bound={:?}, verify_bound={:?})", lower_bound, verify_bound);
1197
1198         match verify_bound {
1199             VerifyBound::IfEq(verify_if_eq_b) => {
1200                 self.eval_if_eq(infcx, param_env, generic_ty, lower_bound, *verify_if_eq_b)
1201             }
1202
1203             VerifyBound::IsEmpty => {
1204                 let lower_bound_scc = self.constraint_sccs.scc(lower_bound);
1205                 self.scc_values.elements_contained_in(lower_bound_scc).next().is_none()
1206             }
1207
1208             VerifyBound::OutlivedBy(r) => {
1209                 let r_vid = self.to_region_vid(*r);
1210                 self.eval_outlives(r_vid, lower_bound)
1211             }
1212
1213             VerifyBound::AnyBound(verify_bounds) => verify_bounds.iter().any(|verify_bound| {
1214                 self.eval_verify_bound(infcx, param_env, generic_ty, lower_bound, verify_bound)
1215             }),
1216
1217             VerifyBound::AllBounds(verify_bounds) => verify_bounds.iter().all(|verify_bound| {
1218                 self.eval_verify_bound(infcx, param_env, generic_ty, lower_bound, verify_bound)
1219             }),
1220         }
1221     }
1222
1223     fn eval_if_eq(
1224         &self,
1225         infcx: &InferCtxt<'tcx>,
1226         param_env: ty::ParamEnv<'tcx>,
1227         generic_ty: Ty<'tcx>,
1228         lower_bound: RegionVid,
1229         verify_if_eq_b: ty::Binder<'tcx, VerifyIfEq<'tcx>>,
1230     ) -> bool {
1231         let generic_ty = self.normalize_to_scc_representatives(infcx.tcx, generic_ty);
1232         let verify_if_eq_b = self.normalize_to_scc_representatives(infcx.tcx, verify_if_eq_b);
1233         match test_type_match::extract_verify_if_eq(
1234             infcx.tcx,
1235             param_env,
1236             &verify_if_eq_b,
1237             generic_ty,
1238         ) {
1239             Some(r) => {
1240                 let r_vid = self.to_region_vid(r);
1241                 self.eval_outlives(r_vid, lower_bound)
1242             }
1243             None => false,
1244         }
1245     }
1246
1247     /// This is a conservative normalization procedure. It takes every
1248     /// free region in `value` and replaces it with the
1249     /// "representative" of its SCC (see `scc_representatives` field).
1250     /// We are guaranteed that if two values normalize to the same
1251     /// thing, then they are equal; this is a conservative check in
1252     /// that they could still be equal even if they normalize to
1253     /// different results. (For example, there might be two regions
1254     /// with the same value that are not in the same SCC).
1255     ///
1256     /// N.B., this is not an ideal approach and I would like to revisit
1257     /// it. However, it works pretty well in practice. In particular,
1258     /// this is needed to deal with projection outlives bounds like
1259     ///
1260     /// ```text
1261     /// <T as Foo<'0>>::Item: '1
1262     /// ```
1263     ///
1264     /// In particular, this routine winds up being important when
1265     /// there are bounds like `where <T as Foo<'a>>::Item: 'b` in the
1266     /// environment. In this case, if we can show that `'0 == 'a`,
1267     /// and that `'b: '1`, then we know that the clause is
1268     /// satisfied. In such cases, particularly due to limitations of
1269     /// the trait solver =), we usually wind up with a where-clause like
1270     /// `T: Foo<'a>` in scope, which thus forces `'0 == 'a` to be added as
1271     /// a constraint, and thus ensures that they are in the same SCC.
1272     ///
1273     /// So why can't we do a more correct routine? Well, we could
1274     /// *almost* use the `relate_tys` code, but the way it is
1275     /// currently setup it creates inference variables to deal with
1276     /// higher-ranked things and so forth, and right now the inference
1277     /// context is not permitted to make more inference variables. So
1278     /// we use this kind of hacky solution.
1279     fn normalize_to_scc_representatives<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
1280     where
1281         T: TypeFoldable<'tcx>,
1282     {
1283         tcx.fold_regions(value, |r, _db| {
1284             let vid = self.to_region_vid(r);
1285             let scc = self.constraint_sccs.scc(vid);
1286             let repr = self.scc_representatives[scc];
1287             tcx.mk_region(ty::ReVar(repr))
1288         })
1289     }
1290
1291     // Evaluate whether `sup_region == sub_region`.
1292     fn eval_equal(&self, r1: RegionVid, r2: RegionVid) -> bool {
1293         self.eval_outlives(r1, r2) && self.eval_outlives(r2, r1)
1294     }
1295
1296     // Evaluate whether `sup_region: sub_region`.
1297     #[instrument(skip(self), level = "debug", ret)]
1298     fn eval_outlives(&self, sup_region: RegionVid, sub_region: RegionVid) -> bool {
1299         debug!(
1300             "sup_region's value = {:?} universal={:?}",
1301             self.region_value_str(sup_region),
1302             self.universal_regions.is_universal_region(sup_region),
1303         );
1304         debug!(
1305             "sub_region's value = {:?} universal={:?}",
1306             self.region_value_str(sub_region),
1307             self.universal_regions.is_universal_region(sub_region),
1308         );
1309
1310         let sub_region_scc = self.constraint_sccs.scc(sub_region);
1311         let sup_region_scc = self.constraint_sccs.scc(sup_region);
1312
1313         // If we are checking that `'sup: 'sub`, and `'sub` contains
1314         // some placeholder that `'sup` cannot name, then this is only
1315         // true if `'sup` outlives static.
1316         if !self.universe_compatible(sub_region_scc, sup_region_scc) {
1317             debug!(
1318                 "sub universe `{sub_region_scc:?}` is not nameable \
1319                 by super `{sup_region_scc:?}`, promoting to static",
1320             );
1321
1322             return self.eval_outlives(sup_region, self.universal_regions.fr_static);
1323         }
1324
1325         // Both the `sub_region` and `sup_region` consist of the union
1326         // of some number of universal regions (along with the union
1327         // of various points in the CFG; ignore those points for
1328         // now). Therefore, the sup-region outlives the sub-region if,
1329         // for each universal region R1 in the sub-region, there
1330         // exists some region R2 in the sup-region that outlives R1.
1331         let universal_outlives =
1332             self.scc_values.universal_regions_outlived_by(sub_region_scc).all(|r1| {
1333                 self.scc_values
1334                     .universal_regions_outlived_by(sup_region_scc)
1335                     .any(|r2| self.universal_region_relations.outlives(r2, r1))
1336             });
1337
1338         if !universal_outlives {
1339             debug!("sub region contains a universal region not present in super");
1340             return false;
1341         }
1342
1343         // Now we have to compare all the points in the sub region and make
1344         // sure they exist in the sup region.
1345
1346         if self.universal_regions.is_universal_region(sup_region) {
1347             // Micro-opt: universal regions contain all points.
1348             debug!("super is universal and hence contains all points");
1349             return true;
1350         }
1351
1352         debug!("comparison between points in sup/sub");
1353
1354         self.scc_values.contains_points(sup_region_scc, sub_region_scc)
1355     }
1356
1357     /// Once regions have been propagated, this method is used to see
1358     /// whether any of the constraints were too strong. In particular,
1359     /// we want to check for a case where a universally quantified
1360     /// region exceeded its bounds. Consider:
1361     /// ```compile_fail
1362     /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1363     /// ```
1364     /// In this case, returning `x` requires `&'a u32 <: &'b u32`
1365     /// and hence we establish (transitively) a constraint that
1366     /// `'a: 'b`. The `propagate_constraints` code above will
1367     /// therefore add `end('a)` into the region for `'b` -- but we
1368     /// have no evidence that `'b` outlives `'a`, so we want to report
1369     /// an error.
1370     ///
1371     /// If `propagated_outlives_requirements` is `Some`, then we will
1372     /// push unsatisfied obligations into there. Otherwise, we'll
1373     /// report them as errors.
1374     fn check_universal_regions(
1375         &self,
1376         mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1377         errors_buffer: &mut RegionErrors<'tcx>,
1378     ) {
1379         for (fr, fr_definition) in self.definitions.iter_enumerated() {
1380             match fr_definition.origin {
1381                 NllRegionVariableOrigin::FreeRegion => {
1382                     // Go through each of the universal regions `fr` and check that
1383                     // they did not grow too large, accumulating any requirements
1384                     // for our caller into the `outlives_requirements` vector.
1385                     self.check_universal_region(
1386                         fr,
1387                         &mut propagated_outlives_requirements,
1388                         errors_buffer,
1389                     );
1390                 }
1391
1392                 NllRegionVariableOrigin::Placeholder(placeholder) => {
1393                     self.check_bound_universal_region(fr, placeholder, errors_buffer);
1394                 }
1395
1396                 NllRegionVariableOrigin::Existential { .. } => {
1397                     // nothing to check here
1398                 }
1399             }
1400         }
1401     }
1402
1403     /// Checks if Polonius has found any unexpected free region relations.
1404     ///
1405     /// In Polonius terms, a "subset error" (or "illegal subset relation error") is the equivalent
1406     /// of NLL's "checking if any region constraints were too strong": a placeholder origin `'a`
1407     /// was unexpectedly found to be a subset of another placeholder origin `'b`, and means in NLL
1408     /// terms that the "longer free region" `'a` outlived the "shorter free region" `'b`.
1409     ///
1410     /// More details can be found in this blog post by Niko:
1411     /// <https://smallcultfollowing.com/babysteps/blog/2019/01/17/polonius-and-region-errors/>
1412     ///
1413     /// In the canonical example
1414     /// ```compile_fail
1415     /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1416     /// ```
1417     /// returning `x` requires `&'a u32 <: &'b u32` and hence we establish (transitively) a
1418     /// constraint that `'a: 'b`. It is an error that we have no evidence that this
1419     /// constraint holds.
1420     ///
1421     /// If `propagated_outlives_requirements` is `Some`, then we will
1422     /// push unsatisfied obligations into there. Otherwise, we'll
1423     /// report them as errors.
1424     fn check_polonius_subset_errors(
1425         &self,
1426         mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1427         errors_buffer: &mut RegionErrors<'tcx>,
1428         polonius_output: Rc<PoloniusOutput>,
1429     ) {
1430         debug!(
1431             "check_polonius_subset_errors: {} subset_errors",
1432             polonius_output.subset_errors.len()
1433         );
1434
1435         // Similarly to `check_universal_regions`: a free region relation, which was not explicitly
1436         // declared ("known") was found by Polonius, so emit an error, or propagate the
1437         // requirements for our caller into the `propagated_outlives_requirements` vector.
1438         //
1439         // Polonius doesn't model regions ("origins") as CFG-subsets or durations, but the
1440         // `longer_fr` and `shorter_fr` terminology will still be used here, for consistency with
1441         // the rest of the NLL infrastructure. The "subset origin" is the "longer free region",
1442         // and the "superset origin" is the outlived "shorter free region".
1443         //
1444         // Note: Polonius will produce a subset error at every point where the unexpected
1445         // `longer_fr`'s "placeholder loan" is contained in the `shorter_fr`. This can be helpful
1446         // for diagnostics in the future, e.g. to point more precisely at the key locations
1447         // requiring this constraint to hold. However, the error and diagnostics code downstream
1448         // expects that these errors are not duplicated (and that they are in a certain order).
1449         // Otherwise, diagnostics messages such as the ones giving names like `'1` to elided or
1450         // anonymous lifetimes for example, could give these names differently, while others like
1451         // the outlives suggestions or the debug output from `#[rustc_regions]` would be
1452         // duplicated. The polonius subset errors are deduplicated here, while keeping the
1453         // CFG-location ordering.
1454         let mut subset_errors: Vec<_> = polonius_output
1455             .subset_errors
1456             .iter()
1457             .flat_map(|(_location, subset_errors)| subset_errors.iter())
1458             .collect();
1459         subset_errors.sort();
1460         subset_errors.dedup();
1461
1462         for (longer_fr, shorter_fr) in subset_errors.into_iter() {
1463             debug!(
1464                 "check_polonius_subset_errors: subset_error longer_fr={:?},\
1465                  shorter_fr={:?}",
1466                 longer_fr, shorter_fr
1467             );
1468
1469             let propagated = self.try_propagate_universal_region_error(
1470                 *longer_fr,
1471                 *shorter_fr,
1472                 &mut propagated_outlives_requirements,
1473             );
1474             if propagated == RegionRelationCheckResult::Error {
1475                 errors_buffer.push(RegionErrorKind::RegionError {
1476                     longer_fr: *longer_fr,
1477                     shorter_fr: *shorter_fr,
1478                     fr_origin: NllRegionVariableOrigin::FreeRegion,
1479                     is_reported: true,
1480                 });
1481             }
1482         }
1483
1484         // Handle the placeholder errors as usual, until the chalk-rustc-polonius triumvirate has
1485         // a more complete picture on how to separate this responsibility.
1486         for (fr, fr_definition) in self.definitions.iter_enumerated() {
1487             match fr_definition.origin {
1488                 NllRegionVariableOrigin::FreeRegion => {
1489                     // handled by polonius above
1490                 }
1491
1492                 NllRegionVariableOrigin::Placeholder(placeholder) => {
1493                     self.check_bound_universal_region(fr, placeholder, errors_buffer);
1494                 }
1495
1496                 NllRegionVariableOrigin::Existential { .. } => {
1497                     // nothing to check here
1498                 }
1499             }
1500         }
1501     }
1502
1503     /// Checks the final value for the free region `fr` to see if it
1504     /// grew too large. In particular, examine what `end(X)` points
1505     /// wound up in `fr`'s final value; for each `end(X)` where `X !=
1506     /// fr`, we want to check that `fr: X`. If not, that's either an
1507     /// error, or something we have to propagate to our creator.
1508     ///
1509     /// Things that are to be propagated are accumulated into the
1510     /// `outlives_requirements` vector.
1511     #[instrument(skip(self, propagated_outlives_requirements, errors_buffer), level = "debug")]
1512     fn check_universal_region(
1513         &self,
1514         longer_fr: RegionVid,
1515         propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1516         errors_buffer: &mut RegionErrors<'tcx>,
1517     ) {
1518         let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1519
1520         // Because this free region must be in the ROOT universe, we
1521         // know it cannot contain any bound universes.
1522         assert!(self.scc_universes[longer_fr_scc] == ty::UniverseIndex::ROOT);
1523         debug_assert!(self.scc_values.placeholders_contained_in(longer_fr_scc).next().is_none());
1524
1525         // Only check all of the relations for the main representative of each
1526         // SCC, otherwise just check that we outlive said representative. This
1527         // reduces the number of redundant relations propagated out of
1528         // closures.
1529         // Note that the representative will be a universal region if there is
1530         // one in this SCC, so we will always check the representative here.
1531         let representative = self.scc_representatives[longer_fr_scc];
1532         if representative != longer_fr {
1533             if let RegionRelationCheckResult::Error = self.check_universal_region_relation(
1534                 longer_fr,
1535                 representative,
1536                 propagated_outlives_requirements,
1537             ) {
1538                 errors_buffer.push(RegionErrorKind::RegionError {
1539                     longer_fr,
1540                     shorter_fr: representative,
1541                     fr_origin: NllRegionVariableOrigin::FreeRegion,
1542                     is_reported: true,
1543                 });
1544             }
1545             return;
1546         }
1547
1548         // Find every region `o` such that `fr: o`
1549         // (because `fr` includes `end(o)`).
1550         let mut error_reported = false;
1551         for shorter_fr in self.scc_values.universal_regions_outlived_by(longer_fr_scc) {
1552             if let RegionRelationCheckResult::Error = self.check_universal_region_relation(
1553                 longer_fr,
1554                 shorter_fr,
1555                 propagated_outlives_requirements,
1556             ) {
1557                 // We only report the first region error. Subsequent errors are hidden so as
1558                 // not to overwhelm the user, but we do record them so as to potentially print
1559                 // better diagnostics elsewhere...
1560                 errors_buffer.push(RegionErrorKind::RegionError {
1561                     longer_fr,
1562                     shorter_fr,
1563                     fr_origin: NllRegionVariableOrigin::FreeRegion,
1564                     is_reported: !error_reported,
1565                 });
1566
1567                 error_reported = true;
1568             }
1569         }
1570     }
1571
1572     /// Checks that we can prove that `longer_fr: shorter_fr`. If we can't we attempt to propagate
1573     /// the constraint outward (e.g. to a closure environment), but if that fails, there is an
1574     /// error.
1575     fn check_universal_region_relation(
1576         &self,
1577         longer_fr: RegionVid,
1578         shorter_fr: RegionVid,
1579         propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1580     ) -> RegionRelationCheckResult {
1581         // If it is known that `fr: o`, carry on.
1582         if self.universal_region_relations.outlives(longer_fr, shorter_fr) {
1583             RegionRelationCheckResult::Ok
1584         } else {
1585             // If we are not in a context where we can't propagate errors, or we
1586             // could not shrink `fr` to something smaller, then just report an
1587             // error.
1588             //
1589             // Note: in this case, we use the unapproximated regions to report the
1590             // error. This gives better error messages in some cases.
1591             self.try_propagate_universal_region_error(
1592                 longer_fr,
1593                 shorter_fr,
1594                 propagated_outlives_requirements,
1595             )
1596         }
1597     }
1598
1599     /// Attempt to propagate a region error (e.g. `'a: 'b`) that is not met to a closure's
1600     /// creator. If we cannot, then the caller should report an error to the user.
1601     fn try_propagate_universal_region_error(
1602         &self,
1603         longer_fr: RegionVid,
1604         shorter_fr: RegionVid,
1605         propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1606     ) -> RegionRelationCheckResult {
1607         if let Some(propagated_outlives_requirements) = propagated_outlives_requirements {
1608             // Shrink `longer_fr` until we find a non-local region (if we do).
1609             // We'll call it `fr-` -- it's ever so slightly smaller than
1610             // `longer_fr`.
1611             if let Some(fr_minus) = self.universal_region_relations.non_local_lower_bound(longer_fr)
1612             {
1613                 debug!("try_propagate_universal_region_error: fr_minus={:?}", fr_minus);
1614
1615                 let blame_span_category = self.find_outlives_blame_span(
1616                     longer_fr,
1617                     NllRegionVariableOrigin::FreeRegion,
1618                     shorter_fr,
1619                 );
1620
1621                 // Grow `shorter_fr` until we find some non-local regions. (We
1622                 // always will.)  We'll call them `shorter_fr+` -- they're ever
1623                 // so slightly larger than `shorter_fr`.
1624                 let shorter_fr_plus =
1625                     self.universal_region_relations.non_local_upper_bounds(shorter_fr);
1626                 debug!(
1627                     "try_propagate_universal_region_error: shorter_fr_plus={:?}",
1628                     shorter_fr_plus
1629                 );
1630                 for fr in shorter_fr_plus {
1631                     // Push the constraint `fr-: shorter_fr+`
1632                     propagated_outlives_requirements.push(ClosureOutlivesRequirement {
1633                         subject: ClosureOutlivesSubject::Region(fr_minus),
1634                         outlived_free_region: fr,
1635                         blame_span: blame_span_category.1.span,
1636                         category: blame_span_category.0,
1637                     });
1638                 }
1639                 return RegionRelationCheckResult::Propagated;
1640             }
1641         }
1642
1643         RegionRelationCheckResult::Error
1644     }
1645
1646     fn check_bound_universal_region(
1647         &self,
1648         longer_fr: RegionVid,
1649         placeholder: ty::PlaceholderRegion,
1650         errors_buffer: &mut RegionErrors<'tcx>,
1651     ) {
1652         debug!("check_bound_universal_region(fr={:?}, placeholder={:?})", longer_fr, placeholder,);
1653
1654         let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1655         debug!("check_bound_universal_region: longer_fr_scc={:?}", longer_fr_scc,);
1656
1657         for error_element in self.scc_values.elements_contained_in(longer_fr_scc) {
1658             match error_element {
1659                 RegionElement::Location(_) | RegionElement::RootUniversalRegion(_) => {}
1660                 // If we have some bound universal region `'a`, then the only
1661                 // elements it can contain is itself -- we don't know anything
1662                 // else about it!
1663                 RegionElement::PlaceholderRegion(placeholder1) => {
1664                     if placeholder == placeholder1 {
1665                         continue;
1666                     }
1667                 }
1668             }
1669
1670             errors_buffer.push(RegionErrorKind::BoundUniversalRegionError {
1671                 longer_fr,
1672                 error_element,
1673                 placeholder,
1674             });
1675
1676             // Stop after the first error, it gets too noisy otherwise, and does not provide more information.
1677             break;
1678         }
1679         debug!("check_bound_universal_region: all bounds satisfied");
1680     }
1681
1682     #[instrument(level = "debug", skip(self, infcx, errors_buffer))]
1683     fn check_member_constraints(
1684         &self,
1685         infcx: &InferCtxt<'tcx>,
1686         errors_buffer: &mut RegionErrors<'tcx>,
1687     ) {
1688         let member_constraints = self.member_constraints.clone();
1689         for m_c_i in member_constraints.all_indices() {
1690             debug!(?m_c_i);
1691             let m_c = &member_constraints[m_c_i];
1692             let member_region_vid = m_c.member_region_vid;
1693             debug!(
1694                 ?member_region_vid,
1695                 value = ?self.region_value_str(member_region_vid),
1696             );
1697             let choice_regions = member_constraints.choice_regions(m_c_i);
1698             debug!(?choice_regions);
1699
1700             // Did the member region wind up equal to any of the option regions?
1701             if let Some(o) =
1702                 choice_regions.iter().find(|&&o_r| self.eval_equal(o_r, m_c.member_region_vid))
1703             {
1704                 debug!("evaluated as equal to {:?}", o);
1705                 continue;
1706             }
1707
1708             // If not, report an error.
1709             let member_region = infcx.tcx.mk_region(ty::ReVar(member_region_vid));
1710             errors_buffer.push(RegionErrorKind::UnexpectedHiddenRegion {
1711                 span: m_c.definition_span,
1712                 hidden_ty: m_c.hidden_ty,
1713                 key: m_c.key,
1714                 member_region,
1715             });
1716         }
1717     }
1718
1719     /// We have a constraint `fr1: fr2` that is not satisfied, where
1720     /// `fr2` represents some universal region. Here, `r` is some
1721     /// region where we know that `fr1: r` and this function has the
1722     /// job of determining whether `r` is "to blame" for the fact that
1723     /// `fr1: fr2` is required.
1724     ///
1725     /// This is true under two conditions:
1726     ///
1727     /// - `r == fr2`
1728     /// - `fr2` is `'static` and `r` is some placeholder in a universe
1729     ///   that cannot be named by `fr1`; in that case, we will require
1730     ///   that `fr1: 'static` because it is the only way to `fr1: r` to
1731     ///   be satisfied. (See `add_incompatible_universe`.)
1732     pub(crate) fn provides_universal_region(
1733         &self,
1734         r: RegionVid,
1735         fr1: RegionVid,
1736         fr2: RegionVid,
1737     ) -> bool {
1738         debug!("provides_universal_region(r={:?}, fr1={:?}, fr2={:?})", r, fr1, fr2);
1739         let result = {
1740             r == fr2 || {
1741                 fr2 == self.universal_regions.fr_static && self.cannot_name_placeholder(fr1, r)
1742             }
1743         };
1744         debug!("provides_universal_region: result = {:?}", result);
1745         result
1746     }
1747
1748     /// If `r2` represents a placeholder region, then this returns
1749     /// `true` if `r1` cannot name that placeholder in its
1750     /// value; otherwise, returns `false`.
1751     pub(crate) fn cannot_name_placeholder(&self, r1: RegionVid, r2: RegionVid) -> bool {
1752         debug!("cannot_name_value_of(r1={:?}, r2={:?})", r1, r2);
1753
1754         match self.definitions[r2].origin {
1755             NllRegionVariableOrigin::Placeholder(placeholder) => {
1756                 let universe1 = self.definitions[r1].universe;
1757                 debug!(
1758                     "cannot_name_value_of: universe1={:?} placeholder={:?}",
1759                     universe1, placeholder
1760                 );
1761                 universe1.cannot_name(placeholder.universe)
1762             }
1763
1764             NllRegionVariableOrigin::FreeRegion | NllRegionVariableOrigin::Existential { .. } => {
1765                 false
1766             }
1767         }
1768     }
1769
1770     /// Finds a good `ObligationCause` to blame for the fact that `fr1` outlives `fr2`.
1771     pub(crate) fn find_outlives_blame_span(
1772         &self,
1773         fr1: RegionVid,
1774         fr1_origin: NllRegionVariableOrigin,
1775         fr2: RegionVid,
1776     ) -> (ConstraintCategory<'tcx>, ObligationCause<'tcx>) {
1777         let BlameConstraint { category, cause, .. } = self
1778             .best_blame_constraint(fr1, fr1_origin, |r| self.provides_universal_region(r, fr1, fr2))
1779             .0;
1780         (category, cause)
1781     }
1782
1783     /// Walks the graph of constraints (where `'a: 'b` is considered
1784     /// an edge `'a -> 'b`) to find all paths from `from_region` to
1785     /// `to_region`. The paths are accumulated into the vector
1786     /// `results`. The paths are stored as a series of
1787     /// `ConstraintIndex` values -- in other words, a list of *edges*.
1788     ///
1789     /// Returns: a series of constraints as well as the region `R`
1790     /// that passed the target test.
1791     pub(crate) fn find_constraint_paths_between_regions(
1792         &self,
1793         from_region: RegionVid,
1794         target_test: impl Fn(RegionVid) -> bool,
1795     ) -> Option<(Vec<OutlivesConstraint<'tcx>>, RegionVid)> {
1796         let mut context = IndexVec::from_elem(Trace::NotVisited, &self.definitions);
1797         context[from_region] = Trace::StartRegion;
1798
1799         // Use a deque so that we do a breadth-first search. We will
1800         // stop at the first match, which ought to be the shortest
1801         // path (fewest constraints).
1802         let mut deque = VecDeque::new();
1803         deque.push_back(from_region);
1804
1805         while let Some(r) = deque.pop_front() {
1806             debug!(
1807                 "find_constraint_paths_between_regions: from_region={:?} r={:?} value={}",
1808                 from_region,
1809                 r,
1810                 self.region_value_str(r),
1811             );
1812
1813             // Check if we reached the region we were looking for. If so,
1814             // we can reconstruct the path that led to it and return it.
1815             if target_test(r) {
1816                 let mut result = vec![];
1817                 let mut p = r;
1818                 loop {
1819                     match context[p].clone() {
1820                         Trace::NotVisited => {
1821                             bug!("found unvisited region {:?} on path to {:?}", p, r)
1822                         }
1823
1824                         Trace::FromOutlivesConstraint(c) => {
1825                             p = c.sup;
1826                             result.push(c);
1827                         }
1828
1829                         Trace::StartRegion => {
1830                             result.reverse();
1831                             return Some((result, r));
1832                         }
1833                     }
1834                 }
1835             }
1836
1837             // Otherwise, walk over the outgoing constraints and
1838             // enqueue any regions we find, keeping track of how we
1839             // reached them.
1840
1841             // A constraint like `'r: 'x` can come from our constraint
1842             // graph.
1843             let fr_static = self.universal_regions.fr_static;
1844             let outgoing_edges_from_graph =
1845                 self.constraint_graph.outgoing_edges(r, &self.constraints, fr_static);
1846
1847             // Always inline this closure because it can be hot.
1848             let mut handle_constraint = #[inline(always)]
1849             |constraint: OutlivesConstraint<'tcx>| {
1850                 debug_assert_eq!(constraint.sup, r);
1851                 let sub_region = constraint.sub;
1852                 if let Trace::NotVisited = context[sub_region] {
1853                     context[sub_region] = Trace::FromOutlivesConstraint(constraint);
1854                     deque.push_back(sub_region);
1855                 }
1856             };
1857
1858             // This loop can be hot.
1859             for constraint in outgoing_edges_from_graph {
1860                 handle_constraint(constraint);
1861             }
1862
1863             // Member constraints can also give rise to `'r: 'x` edges that
1864             // were not part of the graph initially, so watch out for those.
1865             // (But they are extremely rare; this loop is very cold.)
1866             for constraint in self.applied_member_constraints(r) {
1867                 let p_c = &self.member_constraints[constraint.member_constraint_index];
1868                 let constraint = OutlivesConstraint {
1869                     sup: r,
1870                     sub: constraint.min_choice,
1871                     locations: Locations::All(p_c.definition_span),
1872                     span: p_c.definition_span,
1873                     category: ConstraintCategory::OpaqueType,
1874                     variance_info: ty::VarianceDiagInfo::default(),
1875                     from_closure: false,
1876                 };
1877                 handle_constraint(constraint);
1878             }
1879         }
1880
1881         None
1882     }
1883
1884     /// Finds some region R such that `fr1: R` and `R` is live at `elem`.
1885     #[instrument(skip(self), level = "trace", ret)]
1886     pub(crate) fn find_sub_region_live_at(&self, fr1: RegionVid, elem: Location) -> RegionVid {
1887         trace!(scc = ?self.constraint_sccs.scc(fr1));
1888         trace!(universe = ?self.scc_universes[self.constraint_sccs.scc(fr1)]);
1889         self.find_constraint_paths_between_regions(fr1, |r| {
1890             // First look for some `r` such that `fr1: r` and `r` is live at `elem`
1891             trace!(?r, liveness_constraints=?self.liveness_constraints.region_value_str(r));
1892             self.liveness_constraints.contains(r, elem)
1893         })
1894         .or_else(|| {
1895             // If we fail to find that, we may find some `r` such that
1896             // `fr1: r` and `r` is a placeholder from some universe
1897             // `fr1` cannot name. This would force `fr1` to be
1898             // `'static`.
1899             self.find_constraint_paths_between_regions(fr1, |r| {
1900                 self.cannot_name_placeholder(fr1, r)
1901             })
1902         })
1903         .or_else(|| {
1904             // If we fail to find THAT, it may be that `fr1` is a
1905             // placeholder that cannot "fit" into its SCC. In that
1906             // case, there should be some `r` where `fr1: r` and `fr1` is a
1907             // placeholder that `r` cannot name. We can blame that
1908             // edge.
1909             //
1910             // Remember that if `R1: R2`, then the universe of R1
1911             // must be able to name the universe of R2, because R2 will
1912             // be at least `'empty(Universe(R2))`, and `R1` must be at
1913             // larger than that.
1914             self.find_constraint_paths_between_regions(fr1, |r| {
1915                 self.cannot_name_placeholder(r, fr1)
1916             })
1917         })
1918         .map(|(_path, r)| r)
1919         .unwrap()
1920     }
1921
1922     /// Get the region outlived by `longer_fr` and live at `element`.
1923     pub(crate) fn region_from_element(
1924         &self,
1925         longer_fr: RegionVid,
1926         element: &RegionElement,
1927     ) -> RegionVid {
1928         match *element {
1929             RegionElement::Location(l) => self.find_sub_region_live_at(longer_fr, l),
1930             RegionElement::RootUniversalRegion(r) => r,
1931             RegionElement::PlaceholderRegion(error_placeholder) => self
1932                 .definitions
1933                 .iter_enumerated()
1934                 .find_map(|(r, definition)| match definition.origin {
1935                     NllRegionVariableOrigin::Placeholder(p) if p == error_placeholder => Some(r),
1936                     _ => None,
1937                 })
1938                 .unwrap(),
1939         }
1940     }
1941
1942     /// Get the region definition of `r`.
1943     pub(crate) fn region_definition(&self, r: RegionVid) -> &RegionDefinition<'tcx> {
1944         &self.definitions[r]
1945     }
1946
1947     /// Check if the SCC of `r` contains `upper`.
1948     pub(crate) fn upper_bound_in_region_scc(&self, r: RegionVid, upper: RegionVid) -> bool {
1949         let r_scc = self.constraint_sccs.scc(r);
1950         self.scc_values.contains(r_scc, upper)
1951     }
1952
1953     pub(crate) fn universal_regions(&self) -> &UniversalRegions<'tcx> {
1954         self.universal_regions.as_ref()
1955     }
1956
1957     /// Tries to find the best constraint to blame for the fact that
1958     /// `R: from_region`, where `R` is some region that meets
1959     /// `target_test`. This works by following the constraint graph,
1960     /// creating a constraint path that forces `R` to outlive
1961     /// `from_region`, and then finding the best choices within that
1962     /// path to blame.
1963     #[instrument(level = "debug", skip(self, target_test))]
1964     pub(crate) fn best_blame_constraint(
1965         &self,
1966         from_region: RegionVid,
1967         from_region_origin: NllRegionVariableOrigin,
1968         target_test: impl Fn(RegionVid) -> bool,
1969     ) -> (BlameConstraint<'tcx>, Vec<ExtraConstraintInfo>) {
1970         // Find all paths
1971         let (path, target_region) =
1972             self.find_constraint_paths_between_regions(from_region, target_test).unwrap();
1973         debug!(
1974             "path={:#?}",
1975             path.iter()
1976                 .map(|c| format!(
1977                     "{:?} ({:?}: {:?})",
1978                     c,
1979                     self.constraint_sccs.scc(c.sup),
1980                     self.constraint_sccs.scc(c.sub),
1981                 ))
1982                 .collect::<Vec<_>>()
1983         );
1984
1985         let mut extra_info = vec![];
1986         for constraint in path.iter() {
1987             let outlived = constraint.sub;
1988             let Some(origin) = self.var_infos.get(outlived) else { continue; };
1989             let RegionVariableOrigin::Nll(NllRegionVariableOrigin::Placeholder(p)) = origin.origin else { continue; };
1990             debug!(?constraint, ?p);
1991             let ConstraintCategory::Predicate(span) = constraint.category else { continue; };
1992             extra_info.push(ExtraConstraintInfo::PlaceholderFromPredicate(span));
1993             // We only want to point to one
1994             break;
1995         }
1996
1997         // We try to avoid reporting a `ConstraintCategory::Predicate` as our best constraint.
1998         // Instead, we use it to produce an improved `ObligationCauseCode`.
1999         // FIXME - determine what we should do if we encounter multiple `ConstraintCategory::Predicate`
2000         // constraints. Currently, we just pick the first one.
2001         let cause_code = path
2002             .iter()
2003             .find_map(|constraint| {
2004                 if let ConstraintCategory::Predicate(predicate_span) = constraint.category {
2005                     // We currently do not store the `DefId` in the `ConstraintCategory`
2006                     // for performances reasons. The error reporting code used by NLL only
2007                     // uses the span, so this doesn't cause any problems at the moment.
2008                     Some(ObligationCauseCode::BindingObligation(
2009                         CRATE_DEF_ID.to_def_id(),
2010                         predicate_span,
2011                     ))
2012                 } else {
2013                     None
2014                 }
2015             })
2016             .unwrap_or_else(|| ObligationCauseCode::MiscObligation);
2017
2018         // Classify each of the constraints along the path.
2019         let mut categorized_path: Vec<BlameConstraint<'tcx>> = path
2020             .iter()
2021             .map(|constraint| BlameConstraint {
2022                 category: constraint.category,
2023                 from_closure: constraint.from_closure,
2024                 cause: ObligationCause::new(constraint.span, CRATE_DEF_ID, cause_code.clone()),
2025                 variance_info: constraint.variance_info,
2026                 outlives_constraint: *constraint,
2027             })
2028             .collect();
2029         debug!("categorized_path={:#?}", categorized_path);
2030
2031         // To find the best span to cite, we first try to look for the
2032         // final constraint that is interesting and where the `sup` is
2033         // not unified with the ultimate target region. The reason
2034         // for this is that we have a chain of constraints that lead
2035         // from the source to the target region, something like:
2036         //
2037         //    '0: '1 ('0 is the source)
2038         //    '1: '2
2039         //    '2: '3
2040         //    '3: '4
2041         //    '4: '5
2042         //    '5: '6 ('6 is the target)
2043         //
2044         // Some of those regions are unified with `'6` (in the same
2045         // SCC). We want to screen those out. After that point, the
2046         // "closest" constraint we have to the end is going to be the
2047         // most likely to be the point where the value escapes -- but
2048         // we still want to screen for an "interesting" point to
2049         // highlight (e.g., a call site or something).
2050         let target_scc = self.constraint_sccs.scc(target_region);
2051         let mut range = 0..path.len();
2052
2053         // As noted above, when reporting an error, there is typically a chain of constraints
2054         // leading from some "source" region which must outlive some "target" region.
2055         // In most cases, we prefer to "blame" the constraints closer to the target --
2056         // but there is one exception. When constraints arise from higher-ranked subtyping,
2057         // we generally prefer to blame the source value,
2058         // as the "target" in this case tends to be some type annotation that the user gave.
2059         // Therefore, if we find that the region origin is some instantiation
2060         // of a higher-ranked region, we start our search from the "source" point
2061         // rather than the "target", and we also tweak a few other things.
2062         //
2063         // An example might be this bit of Rust code:
2064         //
2065         // ```rust
2066         // let x: fn(&'static ()) = |_| {};
2067         // let y: for<'a> fn(&'a ()) = x;
2068         // ```
2069         //
2070         // In MIR, this will be converted into a combination of assignments and type ascriptions.
2071         // In particular, the 'static is imposed through a type ascription:
2072         //
2073         // ```rust
2074         // x = ...;
2075         // AscribeUserType(x, fn(&'static ())
2076         // y = x;
2077         // ```
2078         //
2079         // We wind up ultimately with constraints like
2080         //
2081         // ```rust
2082         // !a: 'temp1 // from the `y = x` statement
2083         // 'temp1: 'temp2
2084         // 'temp2: 'static // from the AscribeUserType
2085         // ```
2086         //
2087         // and here we prefer to blame the source (the y = x statement).
2088         let blame_source = match from_region_origin {
2089             NllRegionVariableOrigin::FreeRegion
2090             | NllRegionVariableOrigin::Existential { from_forall: false } => true,
2091             NllRegionVariableOrigin::Placeholder(_)
2092             | NllRegionVariableOrigin::Existential { from_forall: true } => false,
2093         };
2094
2095         let find_region = |i: &usize| {
2096             let constraint = &path[*i];
2097
2098             let constraint_sup_scc = self.constraint_sccs.scc(constraint.sup);
2099
2100             if blame_source {
2101                 match categorized_path[*i].category {
2102                     ConstraintCategory::OpaqueType
2103                     | ConstraintCategory::Boring
2104                     | ConstraintCategory::BoringNoLocation
2105                     | ConstraintCategory::Internal
2106                     | ConstraintCategory::Predicate(_) => false,
2107                     ConstraintCategory::TypeAnnotation
2108                     | ConstraintCategory::Return(_)
2109                     | ConstraintCategory::Yield => true,
2110                     _ => constraint_sup_scc != target_scc,
2111                 }
2112             } else {
2113                 !matches!(
2114                     categorized_path[*i].category,
2115                     ConstraintCategory::OpaqueType
2116                         | ConstraintCategory::Boring
2117                         | ConstraintCategory::BoringNoLocation
2118                         | ConstraintCategory::Internal
2119                         | ConstraintCategory::Predicate(_)
2120                 )
2121             }
2122         };
2123
2124         let best_choice =
2125             if blame_source { range.rev().find(find_region) } else { range.find(find_region) };
2126
2127         debug!(?best_choice, ?blame_source, ?extra_info);
2128
2129         if let Some(i) = best_choice {
2130             if let Some(next) = categorized_path.get(i + 1) {
2131                 if matches!(categorized_path[i].category, ConstraintCategory::Return(_))
2132                     && next.category == ConstraintCategory::OpaqueType
2133                 {
2134                     // The return expression is being influenced by the return type being
2135                     // impl Trait, point at the return type and not the return expr.
2136                     return (next.clone(), extra_info);
2137                 }
2138             }
2139
2140             if categorized_path[i].category == ConstraintCategory::Return(ReturnConstraint::Normal)
2141             {
2142                 let field = categorized_path.iter().find_map(|p| {
2143                     if let ConstraintCategory::ClosureUpvar(f) = p.category {
2144                         Some(f)
2145                     } else {
2146                         None
2147                     }
2148                 });
2149
2150                 if let Some(field) = field {
2151                     categorized_path[i].category =
2152                         ConstraintCategory::Return(ReturnConstraint::ClosureUpvar(field));
2153                 }
2154             }
2155
2156             return (categorized_path[i].clone(), extra_info);
2157         }
2158
2159         // If that search fails, that is.. unusual. Maybe everything
2160         // is in the same SCC or something. In that case, find what
2161         // appears to be the most interesting point to report to the
2162         // user via an even more ad-hoc guess.
2163         categorized_path.sort_by(|p0, p1| p0.category.cmp(&p1.category));
2164         debug!("sorted_path={:#?}", categorized_path);
2165
2166         (categorized_path.remove(0), extra_info)
2167     }
2168
2169     pub(crate) fn universe_info(&self, universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
2170         self.universe_causes[&universe].clone()
2171     }
2172
2173     /// Tries to find the terminator of the loop in which the region 'r' resides.
2174     /// Returns the location of the terminator if found.
2175     pub(crate) fn find_loop_terminator_location(
2176         &self,
2177         r: RegionVid,
2178         body: &Body<'_>,
2179     ) -> Option<Location> {
2180         let scc = self.constraint_sccs.scc(r.to_region_vid());
2181         let locations = self.scc_values.locations_outlived_by(scc);
2182         for location in locations {
2183             let bb = &body[location.block];
2184             if let Some(terminator) = &bb.terminator {
2185                 // terminator of a loop should be TerminatorKind::FalseUnwind
2186                 if let TerminatorKind::FalseUnwind { .. } = terminator.kind {
2187                     return Some(location);
2188                 }
2189             }
2190         }
2191         None
2192     }
2193 }
2194
2195 impl<'tcx> RegionDefinition<'tcx> {
2196     fn new(universe: ty::UniverseIndex, rv_origin: RegionVariableOrigin) -> Self {
2197         // Create a new region definition. Note that, for free
2198         // regions, the `external_name` field gets updated later in
2199         // `init_universal_regions`.
2200
2201         let origin = match rv_origin {
2202             RegionVariableOrigin::Nll(origin) => origin,
2203             _ => NllRegionVariableOrigin::Existential { from_forall: false },
2204         };
2205
2206         Self { origin, universe, external_name: None }
2207     }
2208 }
2209
2210 #[derive(Clone, Debug)]
2211 pub struct BlameConstraint<'tcx> {
2212     pub category: ConstraintCategory<'tcx>,
2213     pub from_closure: bool,
2214     pub cause: ObligationCause<'tcx>,
2215     pub variance_info: ty::VarianceDiagInfo<'tcx>,
2216     pub outlives_constraint: OutlivesConstraint<'tcx>,
2217 }