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