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