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