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