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