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