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