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